MrDrProfessorTyler
MrDrProfessorTyler

Reputation: 423

Java: String splitting into multiple elements

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!

Upvotes: 0

Views: 2271

Answers (4)

sarwar026
sarwar026

Reputation: 3821

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

Upvotes: 1

nansen
nansen

Reputation: 2962

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.

Upvotes: 1

holocron
holocron

Reputation: 312

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);
}

Upvotes: 0

Youssef G.
Youssef G.

Reputation: 617

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]);
}

Upvotes: 5

Related Questions