Java 如何在Android中根据给定条件拆分字符串?

Java 如何在Android中根据给定条件拆分字符串?,java,android,string,Java,Android,String,我有一个字符串,12-512-2-15-487-9-98,我想分成两个字符串,如下所示: str1="12-512-2"; str2="15-487-9-98"; 这意味着第一个字符串将包含第三个-之前的字符,第二个字符串将包含第三个-之后的剩余字符 我该怎么做? 我试着使用split-and-concat str[0]+-+str[1]+-+str[2] 但是我想要更简单的答案。像这样试试 String text = "12-512-2-15-487-9-98"; int pos = tex

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

str1="12-512-2";
str2="15-487-9-98";
这意味着第一个字符串将包含第三个-之前的字符,第二个字符串将包含第三个-之后的剩余字符

我该怎么做? 我试着使用split-and-concat str[0]+-+str[1]+-+str[2] 但是我想要更简单的答案。

像这样试试

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-2
System.out.println(second); // 15-487-9-98

我想使用正则表达式似乎更容易

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.group1和m.group2的值是您想要的

另一种方法是在Apache Commons Lang库中查找第三次出现的-的索引,并使用获得的索引调用子字符串。

您可以通过str.indexOf函数获得它,您需要在其中传递字符串的字符和起始索引

以你为例

int indexofSecondOccurance=str.indexOf("-", str.indexOf("-") + 1);  
int finalIndex = str.indexOf("-", indexofSecondOccurance + 1));

然后,您可以按子字符串拆分字符串。

方法是迭代字符串并增加计数器,当您看到-在第3处-它将使用子字符串拆分字符串并提供您在第3处找到的索引时

如果它没有按应有的方式拆分索引,则可能需要对索引进行一些调整

应该是这样的:

     String temp = "12-345-678-44-55-66-77";
    int counter = 0;
    String string1 = "";
    String string2 = "";

    for(int i = 0 ; i<temp.length()-1;i++){
        if(temp.charAt(i) == '-'){
            counter++;
        }
        if(counter == 3){
            string1 = temp.substring(0,i-1);
            string2 = temp.substring(i+1,temp.length()-1);
            System.out.println(string1+" "+string2);
        }
    }

位数是否总是相同的?或者它可以改变哪种语言?Kotlin还是java?@Dor不,他们不是。但是-的数量是一样的。@NicolaGallazzi Java谢谢你的回复,但我想要一种直接分割第三个特殊字符的方法。谢谢你的回复,但我想要一种直接分割第三个特殊字符的方法。请在上面找到我的更新回复,我希望这可能会帮助你:是的,它接近我的答案。非常感谢。谢谢你的回复,但是我想要一种直接拆分第三个特殊字符的方法。谢谢你的回复,但是我想要一个简单的解决方案,从第三个特殊字符-,得到一个子字符串。