我使用下面的代码来查找字符串中第 n 个出现的 ,
(逗号)。一旦我得到这个,我需要获取这次出现(第n次)和下一次出现(第n+1次出现)之间的值
如果我哪里出错了,请告诉我。
int ine=nthOccurence(line,18);
String strErrorCode=line.substring(ine,line.indexOf(",", ine+1));
String errorCode=strErrorCode.substring(1, strErrorCode.length());
功能
public static int nthOccurence(String strLine,int index)
{
char c=',';
int pos = strLine.indexOf(c, index);
while (index-- > 0 && pos != -1)
{
pos = strLine.indexOf(c, pos+1);
// System.out.println("position is " + pos);
}
return pos;
}
谢谢。
最佳答案
这是另一种方法,也更具可读性:
public static String getAt(String st, int pos) {
String[] tokens = st.split(",");
return tokens[pos-1];
}
public static void main(String[] args) {
String st = "one,two,three,four";
System.out.println(getAt(st, 1)); // prints "one"
System.out.println(getAt(st, 2)); // prints "two"
System.out.println(getAt(st, 3)); // prints "three"
}
关于java - 字符串中第 N 次出现的字符并获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19275280/