为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

米脂 2024-01-05 10:00:45
我有一个字符串,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] 但我想要更简单的答案。
查看完整描述

4 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

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


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使用获得的索引进行调用。



查看完整回答
反对 回复 2024-01-05
?
慕斯709654

TA贡献1840条经验 获得超5个赞

尝试这样


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


查看完整回答
反对 回复 2024-01-05
?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

str.indexOf()您可以通过需要传递字符串的字符和起始索引的函数来获取它

对于你的例子

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

之后,您可以将字符串拆分为substring()


查看完整回答
反对 回复 2024-01-05
?
慕码人8056858

TA贡献1803条经验 获得超6个赞

这个想法是迭代字符串并增加计数器,当您

在第三个“-”处看到“-”时,它将使用子字符串分割字符串并提供您在第三个“-”处找到的索引。


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


它应该看起来像这样:


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

        }

    }


查看完整回答
反对 回复 2024-01-05
  • 4 回答
  • 0 关注
  • 67 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信