【问题标题】:How do I count the number of times a sequence occurs in a Java string? [closed]如何计算一个序列在 Java 字符串中出现的次数? [关闭]
【发布时间】:2011-03-07 18:52:15
【问题描述】:

我有一个看起来像这样的字符串:

"Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!". 

我想计算is 在字符串中的次数。

如何在 Java 中做到这一点?

【问题讨论】:

  • 你能发布你自己尝试过的东西吗?那么:“是幸福吗?”
  • @Bart Kiers 然后我确定我们可以只寻找“is”而不是“is”来避免这种情况;)
  • "你不明白它是什么。"
  • 通过寻找 " is ",你会错过:" is," and "is!"

标签: java string


【解决方案1】:

一个简单的方法是使用Apache StringUtils countMatches

StringUtils.countMatches("Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!", "is");

【讨论】:

  • 或使用 Spring Framework StringUtils.countOccurrencesOf(string, "is");
  • Spring StringUtils 不是主要用于框架内吗?意思是,它有效,但 Apache 在这方面显然更好。
  • 效果很好。谢谢。
【解决方案2】:
int index = input.indexOf("is");
int count = 0;
while (index != -1) {
    count++;
    input = input.substring(index + 1);
    index = input.indexOf("is");
}
System.out.println("No of *is* in the input is : " + count);

【讨论】:

  • @jzd 同意,感谢指出错误。
  • @asgs,我删除了我的反对票。感谢您的修复。
  • @asgs,您无法取消删除 cmets,因为您在前五分钟内编辑了答案,所以没有修订历史记录。所以没什么可学的。
  • 你也可以使用 index = input.indexOf("is", index+1) 代替 substring 然后 indexOf。没有分析,我不确定,但怀疑这会更快。它也少了 1 行代码;)
  • 许多误报,例如“miss”、“bliss”。它也漏掉了大写的“Is”、“IS”或“iS”。因此,尽管 OP 已经接受了答案,但我还是给了一个-1。
【解决方案3】:

这考虑了“替换”的长度

String text = "a.b.c.d";
String replace = ".";
int count = (text.length()- (text.replaceAll(replace, "").length())) / replace.length();
System.out.println(count)

【讨论】:

    【解决方案4】:
    String haystack = "Hello my is Joeseph. It is very nice to meet you. What a wonderful day it is!";
    haystack.toLowerCase();
    String needle = "is";
    
    int numNeedles = 0;
    
    int pos = haystack.indexOf(needle);
    
        while(pos >= 0 ){
    
          pos = pos + 1;
          numNeedles = numNeedles + 1;
    
          pos = haystack.indexOf(needle,pos);
    
        }
    
     System.out.println("the num of " +needle+ "= " +numNeedles);
    

    【讨论】:

    • char 类型的变量什么时候可以容纳多个字符?
    • 注意到我的错误并编辑了
    【解决方案5】:

    如果您更喜欢正则表达式,这里有一个正则表达式解决方案:

    String example = "Hello my is Joeseph. It is very nice to meet you. isWhat a wonderful day it is!";
    Matcher m = Pattern.compile("\\bis\\b").matcher(example);
    
    int matches = 0;
    while(m.find())
        matches++;
    
    System.out.println(matches);
    

    在这种情况下,“isWhat”中的“is”被忽略,因为模式中的 \b 边界匹配器

    【讨论】:

      【解决方案6】:

      拆分每个“”(空白)并使用循环检查输出的字符串[]

      【讨论】:

      • 如果他要检查的字符串中有空格怎么办?
      • 在这种情况下,他不会计算字符串 >_
      【解决方案7】:

      您可以找到code here。 奇怪的是,它看起来像罗比的那个。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-04
        • 2021-07-06
        • 2023-01-28
        • 1970-01-01
        • 2021-01-27
        • 2014-11-14
        • 2011-06-14
        • 2019-03-12
        相关资源
        最近更新 更多