Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into 2 strings based on a delimiter

Tags:

java

string

Does anybody know if there is a solid library based method to achieve the following.

Say I have the string

"name1, name2, name3, name4" 

and I want to parse it into 2 strings based on the comma delimiter.

I would like the strings to look like this:

string1 = "name1";
string2 = "name2, name3, name4";  

Any ideas?

like image 263
mAndroid Avatar asked Oct 03 '11 06:10

mAndroid


2 Answers

you could use yourString.split(", ", 2).

String str = "name1, name2, name3, name4";

String[] parts = str.split(", ", 2);
String string1 = parts[0];
String string2 = parts[1];

System.out.println(string1);  // prints name1
System.out.println(string2);  // prints name2, name3, name4

You could also use yourString.indexOf(", ") and yourString.substring(...).

like image 90
aioobe Avatar answered Nov 15 '22 22:11

aioobe


Pattern pattern = Pattern.compile(", *");
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
    string1 = inputString.substring(0, matcher.start());
    string2 = inputString.substring(matcher.end());
}
like image 41
Maurice Perry Avatar answered Nov 15 '22 23:11

Maurice Perry