簡體   English   中英

字符串中字符的第N次出現並獲得值

[英]Nth occurence of character in string and get value

我使用下面的代碼,找到的第n次出現,在字符串中(逗號)。 而一旦得到,我需要獲取此事件(nth)與下一個事件(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"
}

像這樣嗎

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM