Java: Splitting a string
In java I have a method that recieves a string that looks like:
"Name ID CSVofInts"
It's purpose is to create a new object with the name, ID and then pass in 开发者_开发问答the CSV as an int array.
How do you split such a string?
Try this:
String items [] = str.split(" ", 3);
String csv [] = items[2].split(",");
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)
Number of approaches:
String[] splitArrayOfStrings = theString.split("delimiter");
Or
You could utilize the StringTokenizer
class for more flexible handling
you can use the tokenizer class.
EX:
StringTokenizer st = new StringTokenizer("this is a test");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
will output
this
is
a
test
Try the Java string split() function.
public String[] split(String regex)
The string "boo:and:foo", for example, yields the following results with these expressions:
Regex -> ":"
Result ->
{ "boo", "and", "foo" }
Returns an array of strings. :)
Chop off the first two fields by simply iterating over the string and finding the first two words, then the ints can be split with substring.split(",");
精彩评论