【问题标题】:How to find how many times does a string object repeat in java?如何在java中找到一个字符串对象重复了多少次?
【发布时间】:2013-03-31 22:48:21
【问题描述】:

我必须字符串对象:

String first = "/Some object that has a loop in it object/";
String second = "object";

我需要做的是找出第二个对象在第一个对象中重复了多少次,你能告诉我怎么做吗?

【问题讨论】:

    标签: java string object


    【解决方案1】:

    这里你只需要两个变量并在循环条件中进行所有检查。

    int pos = 0;
    int count= 0;
    while (first.indexOf(second, pos) >= 0) {
        count++;
        pos = first.indexOf(second, pos) + 1;
    }
    
    System.out.println(count);
    

    【讨论】:

      【解决方案2】:

      我知道这是一个较老的话题,但在我脑海中,你可以使用递归:

      // Recursive routine to find the xth repeat of a string
      public int atIndex(String searchin, String searchfor, int whichone, int pos) {
          return atIndex(searchin, searchfor, whichone, pos, 0);
      }
      
      public int atIndex(String searchin, String searchfor, int whichone, int pos, int recursed) {
          return (whichone>0?atIndex(searchin, searchfor, --whichone, searchin.indexOf(searchfor,pos)+1,++recursed):(recursed==0?-1:pos-1));
      }
      

      我是 Java 新手,所以可能存在我不知道的速度或资源问题,但稍作测试应该可以解决任何问题。

      要调用它,你可以使用:

          String HL7Test="MSH|^~\\&|EPIC|EPICADT|SMS|SMSADT|199912271408|CHARRIS|ADT^A04|1817457" ;
          System.out.println(atIndex(HL7Test, "|", 4, 0));
      

      希望这会有所帮助。

      【讨论】:

      • 许多编程语言中最宝贵的资源是调用栈。您可以轻松地将其展开成一个循环,这将使其更加稳定。您的代码可以命中,请原谅双关语,stack overflow
      【解决方案3】:

      使用这行在后台使用正则表达式:

      String[] parts = first.split(second);
      

      String second 在 String first 中出现 (parts.length - 1) 次。就是这样。

      编辑:

      为防止在字符串second 可能包含正则表达式特定字符的情况下可能出现不需要的结果,您可以在将其传递给split() 方法时使用Pattern.quote(second),正如其中一位评论员所建议的那样。

      【讨论】:

      • 我建议在拆分中使用 Pattern.quote - 谁知道第二个 String 中的内容。
      • @bmorris591 你能举例说明我的代码可能存在的错误吗?
      • 如果第二个字符串包含一些正则表达式,例如 $ 或 ( 或 [,那么拆分将解释正则表达式并返回非常奇怪的东西,甚至可能抛出异常。
      • @bmorris591 谢谢兄弟的启发。请看我的编辑。
      • split(re) 默认会删除数组末尾的空字符串,这会导致该方法给出错误的结果。您需要使用split(re, -1) 来保存它们。
      【解决方案4】:

      使用这个:

       String first = "/Some object that has a loop in it object/";
           String second = "object";
           Pattern pattern = Pattern.compile(second);
           Matcher matcher = pattern.matcher(first) ;
           long count = 0;
           while(matcher.find()) {
               count ++;
      
           }
           System.out.println(count);
      

      【讨论】:

        【解决方案5】:

        使用regex,例如:

        import java.util.regex.*;
        
        class Test {
            public static void main(String[] args) {
                String hello = "HelloxxxHelloxxxHello"; //String you want to 'examine'
                Pattern pattern = Pattern.compile("Hello"); //Pattern string you want to be matched
                Matcher  matcher = pattern.matcher(hello); 
        
                int count = 0;
                while (matcher.find())
                    count++; //count any matched pattern
        
                System.out.println(count);    // prints how many pattern matched
            }
        }
        

        来源:java regex match count

        【讨论】:

        • 确保引用正则表达式,谁知道第二个 String 中的内容。
        • 对于输入“ababab”,返回 1,而基于 indexOf 的解决方案返回 2。
        • @Betlista:阅读 indexOf 解决方案中的评论。 +1 查找重叠匹配。 + needle.length() 查找不重叠的匹配项。此方法在这里找到不重叠的匹配项
        【解决方案6】:

        您可以将String 拆分为第二个String 并计算结果数组的长度,它将多出一个元素的出现次数。或者您可以使用PatternMatcher,这是一种稍微合适的方法。

        public static void main(String[] args) throws UnsupportedEncodingException, IOException {
            String first = "/Some object that has a loop in it object/";
            String second = "object";
        
            System.out.println(first.split(Pattern.quote(second)).length - 1);
        
            final Pattern pattern = Pattern.compile(Pattern.quote(second));
            final Matcher matcher = pattern.matcher(first);
            int count = 0;
            while (matcher.find()) {
                count++;
            }
        
            System.out.println(count);
        
        }
        

        不要忘记使用Pattern.quote以防万一。

        【讨论】:

          【解决方案7】:

          尝试如下...

          String str = "/Some object that has a loop in it object/";
          String findStr = "object";
          int lastIndex = 0;
          int count =0;
          
          while(lastIndex != -1){
          
                 lastIndex = str.indexOf(findStr,lastIndex);
          
                 if( lastIndex != -1){
                       count ++;
                       lastIndex+=findStr.length();
                }
          }
          System.out.println(count);
          

          【讨论】:

            【解决方案8】:

            最简单的方法是在循环中使用indexOf,每次找到单词时都会推进起始索引:

            int ind = 0;
            int cnt = 0;
            while (true) {
                int pos = first.indexOf(second, ind);
                if (pos < 0) break;
                cnt++;
                ind = pos + 1; // Advance by second.length() to avoid self repetitions
            }
            System.out.println(cnt);
            

            如果一个单词包含自我重复,这将多次查找该单词。请参阅上面的评论以避免此类“重复”发现。

            Demo on ideone.

            【讨论】:

            • 谢谢,一切都做了。
            猜你喜欢
            • 2017-04-28
            • 2021-12-25
            • 2023-03-30
            • 2016-06-19
            • 1970-01-01
            • 2012-05-04
            • 1970-01-01
            • 1970-01-01
            • 2012-12-06
            相关资源
            最近更新 更多