0

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?

1
  • Can you show a couple example rows? I'm wondering if the Name, ID, and CSV data have any extra spaces, etc... Commented Apr 14, 2011 at 2:24

5 Answers 5

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2

Number of approaches:

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

Or

You could utilize the StringTokenizer class for more flexible handling

Comments

1

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

Comments

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.