Can you pull apart a string?
I'm storing a string in a database with a value such as "020734". I would like to be able to pull the string apart.
I have:
String values = "020734";
I need:
String values = "020734";
String value1 = "02";
String value2 = "07";
String value3 = "34";
Could you guys poss开发者_StackOverflow中文版ibly point me in a general direction?
Erm, how about value1 = values.substring(0, 2); value2 = values.substring(2,4)
...etc? That will get you two characters at a time from the string.
checkout String.substring
.
String values = "020734";
String value1 = values.substring(0, 2);
String value2 = values.substring(2, 4);
String value3 = values.substring(4, 6);
Well, if you always know the widths of the values you want then you could do the following:
String remainder = startString;
while (remainder.length() >= 2) {
String newPart = remainder.substring(0, 2);
// you can do something with each part
remainder = remainder.substring(2, remainder.length());
}
This will break any string up into 2 character chunks.
You can view the substring()
documentation here:
http://download-llnw.oracle.com/javase/6/docs/api/java/lang/String.html#substring%28int,%20int%29
精彩评论