java - 字符串中第 N 次出现的字符并获取值

标签 java string find-occurrences

我使用下面的代码来查找字符串中第 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/

相关文章:

java - 打包 Servlet(编译时出现符号错误)

java - Oracle 和 Jdbc 以及 OraclePreparedStatement#setPlsqlIndexTable 和 java.util.Date

java - Hibernate Map ID 自动从字段中获取

java - Maven 编译无提示地失败 - Unresolved 编译问题

c++ - 如何在 VS 调试器中查看 C++ 中动态字符串数组的内容

PHP Mysql自动报价?

java - 如何跨转换跟踪字符串中的原始字符位置?

python - 访问列表中的重复元素并打印其旁边的元素

clojure - 计算集合中元素的连续出现次数

javascript - 计算数组中字符串的出现次数(javascript)