Snow_Mac
Snow_Mac

Reputation: 5797

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?

Upvotes: 0

Views: 282

Answers (5)

Matthew Cox
Matthew Cox

Reputation: 13682

Number of approaches:

String[] splitArrayOfStrings = theString.split("delimiter");

Or

You could utilize the StringTokenizer class for more flexible handling

Upvotes: 2

sverre
sverre

Reputation: 6919

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(",");

Upvotes: 0

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. :)

Upvotes: 0

Drew
Drew

Reputation: 171

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

Upvotes: 1

Joshua Martell
Joshua Martell

Reputation: 7212

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)

Upvotes: 3

Related Questions