第N次出现字符串并获取值

时间:2013-10-09 14:45:13

标签: java string find-occurrences

我使用以下代码在字符串中查找第{n {1}}个逗号。一旦我得到这个,我需要得到这个出现(第n次)和下次出现(第n + 1次出现)之间的值

如果我在某个地方出错,请告诉我。

,

功能

 int ine=nthOccurence(line,18);  
         String strErrorCode=line.substring(ine,line.indexOf(",", ine+1));
String errorCode=strErrorCode.substring(1, strErrorCode.length());

感谢。

2 个答案:

答案 0 :(得分:2)

这是一种替代方法,也更具可读性:

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"
}

答案 1 :(得分:2)

这样的东西?

public static int nthOccurence(String strLine,int index){
  String[] items = strLine.split(",");
  if (items.length>=index)
      return items[index];
  else
      return "";//whatever you want to do it there's not enough commas
}
相关问题