我有一个字符串12-512-2-15-487-9-98
,我想分成两个字符串,如下所示:
str1="12-512-2";
str2="15-487-9-98";
这意味着第一个字符串将包含第三个-
之前的字符,第二个字符串将包括之后的剩余字符。
我该怎么做?我使用split("-")
和concatstr[0]+"-"+str[1]+"-"+str[2]
进行了尝试但我想要更简单的答案。
我想使用regex似乎更容易?
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来查找-
第三次出现的索引,并使用获得的索引调用substring
。
像这样尝试
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
您可以通过str.indexOf()
函数获得它,在这里您需要传递字符串的字符和起始索引
例如
int indexofSecondOccurance=str.indexOf("-", str.indexOf("-") + 1);
int finalIndex = str.indexOf("-", indexofSecondOccurance + 1));
之后,您可以通过substring()
分割字符串。
我们的想法是迭代字符串并增加计数器,当您在第三个"-"处看到"-"时,它将使用子字符串拆分字符串,并提供您在.处找到的第三个"-"的索引
如果指数没有按应有的方式进行拆分,它可能需要对指数进行一点调整。
它应该是这样的:
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);
}
}