【问题标题】:How to return the next indexOf after a previous?如何在上一个之后返回下一个 indexOf?
【发布时间】:2013-04-24 11:25:34
【问题描述】:

例如:

str = "(a+b)*(c+d)*(e+f)"
str.indexOf("(") = 0
str.lastIndexOf("(") = 12

如何获取第二个括号中的索引? (c+d)

【问题讨论】:

    标签: java string indexof


    【解决方案1】:
    int first  = str.indexOf("(");
    int next = str.indexOf("(", first+1);
    

    看看API Documentation

    【讨论】:

      【解决方案2】:

      试试这个:

       String word = "(a+b)*(c+d)*(e+f)";
       String c = "(";
        for (int index = word.indexOf(c);index >= 0; index = word.indexOf(c, index + 1)) {
             System.out.println(index);//////here you will get all the index of  "("
          }
      

      【讨论】:

      • @baraky : index >= 0; 是 for 循环中的条件,所以很抱歉我再次回滚我的答案:(
      • 7 年后仍然有用:)。
      【解决方案3】:

      您可以使用来自 Apache Commons 的 StringUtils,在这种情况下是

      StringUtils.indexof(str, ")", str.indexOf(")") + 1);
      

      想法是在最后一个参数中可以指定起始位置,这样就可以避免第一个“)”。

      【讨论】:

        【解决方案4】:
        • 反复使用charAt()
        • 反复使用indexOf()

        试试这个简单的通用解决方案:

            int index =0;
            int resultIndex=0;
            for (int i = 0; i < str.length(); i++){
                if (str.charAt(i) =='('){
                    index++;
                    if (index==2){
                    resultIndex =i;
                    break;
                    }
                }
            }
        

        【讨论】:

          【解决方案5】:

          我觉得有更好的方法!!!

          String str = "(a+b)*(c+d)*(e+f)";
          str = str.replace(str.substring(str.lastIndexOf("*")), "");
          int idx = str.lastIndexOf("(");
          

          和“(c+d)”:

             str = str.substring(idx);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-08-26
            • 1970-01-01
            • 2021-01-01
            • 1970-01-01
            • 2014-02-19
            • 2020-05-26
            • 2017-07-11
            相关资源
            最近更新 更多