Android中如何根据给定条件分割字符串?

我有一个字符串,12-512-2-15-487-9-98我想分成两个字符串,如下所示:

str1="12-512-2";
str2="15-487-9-98";

这意味着第一个字符串将包含 Third 之前的字符-,第二个字符串将包含其后的剩余字符。

我怎样才能做到这一点?我尝试使用split("-")and concatstr[0]+"-"+str[1]+"-"+str[2] 但我想要更简单的答案。


米脂
浏览 74回答 4
4回答

白衣染霜花

我想使用正则表达式似乎更容易?String line = "12-512-2-15-487-9-98";String pattern = "(\\d+-\\d+-\\d+)-(\\d+-\\d+-\\d+-\\d+)";Pattern r = Pattern.compile(pattern);Matcher m = r.matcher(line);if (m.find( )) {  System.out.println("Found value: " + m.group(0) );  System.out.println("Found value: " + m.group(1) );  System.out.println("Found value: " + m.group(2) );} else {  System.out.println("NO MATCH");}m.group(1)和的值m.group(2)就是你想要的。另一种方法是使用Apache Commons Lang 库中的StringUtils.ordinalIndexOf来查找第 3 次出现的索引-,并substring使用获得的索引进行调用。

慕斯709654

尝试这样String text = "12-512-2-15-487-9-98";int pos = text.indexOf('-', 1 + text.indexOf('-', 1 + text.indexOf('-')));String first = text.substring(0, pos);String second = text.substring(pos+1);System.out.println(first); // 12-512-2System.out.println(second); // 15-487-9-98

哆啦的时光机

str.indexOf()您可以通过需要传递字符串的字符和起始索引的函数来获取它对于你的例子int indexofSecondOccurance=str.indexOf("-", str.indexOf("-") + 1);   int finalIndex = str.indexOf("-", indexofSecondOccurance + 1));之后,您可以将字符串拆分为substring()。

慕码人8056858

这个想法是迭代字符串并增加计数器,当您在第三个“-”处看到“-”时,它将使用子字符串分割字符串并提供您在第三个“-”处找到的索引。如果它没有按应有的方式分割索引,则可能需要对索引进行一些调整。它应该看起来像这样:&nbsp; &nbsp; &nbsp;String temp = "12-345-678-44-55-66-77";&nbsp; &nbsp; int counter = 0;&nbsp; &nbsp; String string1 = "";&nbsp; &nbsp; String string2 = "";&nbsp; &nbsp; for(int i = 0 ; i<temp.length()-1;i++){&nbsp; &nbsp; &nbsp; &nbsp; if(temp.charAt(i) == '-'){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(counter == 3){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string1 = temp.substring(0,i-1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; string2 = temp.substring(i+1,temp.length()-1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(string1+" "+string2);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java