开发者

Split string into 2 strings based on a delimiter

开发者 https://www.devze.com 2023-04-10 09:34 出处:网络
Does anybody know if there is a solid library based method to achieve the following. Say I have the string

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

Say I have the string

"na开发者_StackOverflow社区me1, 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?


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


Pattern pattern = Pattern.compile(", *");
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
    string1 = inputString.substring(0, matcher.start());
    string2 = inputString.substring(matcher.end());
}


String s = "hello=goodmorning,2,1"
String[] str = s.split("=");  //now str[0] is "hello" and str[1] is "goodmorning,2,1"
String str1 = str[0];  //hello
String[] str2 = str[1].split(",");  //now str2[0] is "goodmorning" and str2[1] is "2,1"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号