java吧 关注:1,271,337贴子:12,780,624
  • 23回复贴,共1

怎么能比较好的获得子字符串在字符串中第N次出现索引

只看楼主收藏回复

如题


1楼2014-09-03 16:27回复
    除了一次次查还有别的变法么


    IP属地:辽宁2楼2014-09-03 16:30
    收起回复
      2025-07-27 14:54:36
      广告
      不感兴趣
      开通SVIP免广告
      public static int getCharacterPosition(String string,String substring,int count){
      //这里是获取"/"符号的位置
      Matcher slashMatcher = Pattern.compile(substring).matcher(string);
      int mIdx = 0;
      while(slashMatcher.find()) {
      mIdx++;
      //当"/"符号第三次出现的位置
      if(mIdx == count){
      break;
      }
      }
      return slashMatcher.start();
      }
      已经找到并改写 ,大家可以参考


      3楼2014-09-03 16:40
      收起回复
        不用谢


        4楼2014-09-03 16:41
        回复
          public int xxx(int x,String str,String s){
          int count=0;
          for(int i=1;i<x;i++){
          count=s.indexOf(str, int count);
          }
          return count;
          }


          IP属地:重庆5楼2014-09-03 16:44
          收起回复
            public class Test {
            /**
            * @param args
            */
            public static void main(String[] args) {
            System.out.println(xxx(3,"a","saggasssags"));;
            }
            public static int xxx(int x,String str,String s){
            int count=0;
            for(int i=1;i<=x;i++){
            count=s.indexOf(str,count+1);
            }
            return count;
            }
            }


            IP属地:重庆6楼2014-09-03 16:49
            收起回复
              public class Test {
              /**
              * @param args
              */
              public static void main(String[] args) {
              System.out.println(xxx(5, "a", "saggasssags"));
              }
              public static int xxx(int x, String str, String s) {
              int count = 0;
              for (int i = 1; i <= x; i++) {
              count = s.indexOf(str, count + 1);
              if (count == -1) {
              return count;
              }
              }
              return count;
              }
              }


              IP属地:重庆7楼2014-09-03 16:53
              回复
                这种问题,aaaa中查询aa到底算几个?2还是3?
                如果是2那么ls的算法又出问题,我果然是坏人


                IP属地:辽宁8楼2014-09-03 17:22
                收起回复
                  2025-07-27 14:48:36
                  广告
                  不感兴趣
                  开通SVIP免广告
                  public static int getIndex(String str, String s, int count) {
                  if (count == 0)
                  return -1;
                  int len = s.length();
                  int index = -1 - len;
                  while (count > 0 && (index = str.indexOf(s, index + len)) != -1) {
                  count--;
                  }
                  return index;
                  }
                  秀下限 @lx5266


                  IP属地:辽宁9楼2014-09-03 17:34
                  回复