0

I am having a difficult time figuring out how to split a string like the one following:

String str = "hi=bye,hello,goodbye,pickle,noodle

This string was read from a text file and I need to split the string into each element between the commas. So I would need to split each element into their own string no matter what the text file reads. Keep in mind, each element could be any length and there could be any amount of elements which 'hi' is equal to. Any ideas? Thanks!

4 Answers 4

5

use split!

String[] set=str.split(",");

then access each string as you need from set[...] (so lets say you want the 3rd string, you would say: set[2]).

As a test, you can print them all out:

for(int i=0; i<set.length;i++){
    System.out.println(set[i]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

or to use Arrays.toString(set) [for test]
Split is great because you can use regular expressions. For example: str.split(",\\s*") That code will split the source string (str) in each comma and zero or more (*) spaces.
Thank you! I can't believe I have never heard of this method before... Thanks!
Don't forget to use split("=") first to extract the name--hi in this case.
1

If you need a bit more advanced approach, I suggest guava's Splitter class:

Iterable<String> split = Splitter.on(',')
                                 .omitEmptyStrings()
                                 .trimResults()
                                 .split(" bye,hello,goodbye,, , pickle, noodle  ");

This will get rid of leading or trailing whitespaces and omit blank matches. The class has some more cool stuff in it like splitting your String into key/value pairs.

Comments

1
str = str.subString(indexOf('=')+1); // remove "hi=" part
String[] set=str.split(",");

Comments

0

I'm wondering: Do you mean to split it as such:

"hi=bye"
"hi=hello"
"hi=goodbye"
"hi=pickle"
"hi=noodle"

Because a simple split(",") will not do this. What's the purpose of having "hi=" in your given string?

Probably, if you mean to chop hi= from the front of the string, do this instead:

String input = "hi=bye,hello,goodbye,pickle,noodle";
String hi[] = input.split(",");
hi[0] = (hi[0].split("="))[1];
for (String item : hi) {
    System.out.println(item);
}

1 Comment

Yes, I am pretty sure that i what he/she is looking for, although I did not go that far as split can be used once again to get hi at the beginning and combining strings should be relatively easy to figure out from there. Either way, it seemed the difficult was in splitting up the string, rather than applying "hi=" to all of them.

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.