【问题标题】:Java count pattern in String [duplicate]字符串中的Java计数模式[重复]
【发布时间】:2017-10-14 18:39:55
【问题描述】:

假设你有一个方法,它接受一个模式和一个完整的字符串......

方法如下:

public int count(String pattern, String input) { 
    int count = 0;
    // How to implement the number of occurrences of the pattern?
} 

所以,输入可能是这样的:

String input = "sdbwedfddfbcaeeudhsomeothertestddtfdonemoredfdsatdevdb";

String pattern = "ddt";

int result = count(pattern, input);

迭代和查找“ddt”出现的最有效方法(就复杂性而言)是什么?

【问题讨论】:

    标签: java


    【解决方案1】:

    一个简单的方法是根据给定的patternsplitString

    int result = input.split(pattern,-1).length - 1;
    

    工作原理:

    .split(pattern, -1)  -> split the String into an array according to the pattern given, -1 (negative limit) means the pattern will be applied as many times as possible.
    .length  -> take the length of the array
    -1 -> the logic requires counting the splitter (i.e. pattern), so if there is only one occurrence, that will split it into two , when subtract 1 -> it gives the count
    

    【讨论】:

      【解决方案2】:

      您可以使用PatternMatcher 类,例如:

      public int count(String pattern, String input) { 
          int count = 0;
          Pattern patternObject = Pattern.compile(pattern);
          Matcher matcher = patternObject.matcher(input);
          while(matcher.find()){
              count++;
          }
          return count;
      } 
      

      【讨论】:

        【解决方案3】:

        你可以的

        public int count(String pattern, String input) { 
            int i = (input.length()-input.replace(pattern, "").length())/pattern.length();
            return i;
        }
        

        甚至更短

        public int count(String pattern, String input) { 
            return (input.split(pattern, -1).length-1);
        }
        

        【讨论】:

          猜你喜欢
          • 2014-07-04
          • 2012-09-26
          • 1970-01-01
          • 1970-01-01
          • 2019-04-12
          • 2022-01-02
          • 2020-08-17
          • 2021-02-02
          相关资源
          最近更新 更多