4 回答

TA貢獻(xiàn)1796條經(jīng)驗 獲得超10個贊
我想使用正則表達(dá)式似乎更容易?
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 次出現(xiàn)的索引-
,并substring
使用獲得的索引進(jìn)行調(diào)用。

TA貢獻(xiàn)1840條經(jīng)驗 獲得超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

TA貢獻(xiàn)1779條經(jīng)驗 獲得超6個贊
str.indexOf()
您可以通過需要傳遞字符串的字符和起始索引的函數(shù)來獲取它
對于你的例子
int indexofSecondOccurance=str.indexOf("-", str.indexOf("-") + 1); int finalIndex = str.indexOf("-", indexofSecondOccurance + 1));
之后,您可以將字符串拆分為substring()
。

TA貢獻(xiàn)1803條經(jīng)驗 獲得超6個贊
這個想法是迭代字符串并增加計數(shù)器,當(dāng)您
在第三個“-”處看到“-”時,它將使用子字符串分割字符串并提供您在第三個“-”處找到的索引。
如果它沒有按應(yīng)有的方式分割索引,則可能需要對索引進(jìn)行一些調(diào)整。
它應(yīng)該看起來像這樣:
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);
}
}
添加回答
舉報