【问题标题】:Split a String using split function to count number of "that" [duplicate]使用拆分函数拆分字符串以计算“那个”的数量 [重复]
【发布时间】:2018-02-11 20:40:52
【问题描述】:
String str = "ABthatCDthatBHthatIOthatoo";     
System.out.println(str.split("that").length-1);

从这里我得到 4. 这是正确的,但如果最后一个后面没有任何字母,那么它会显示错误的答案“3”,如下所示:

String str = "ABthatCDthatBHthatIOthat";
System.out.println(str.split("that").length-1);

我想计算给定字符串中“那个”字的出现次数。

【问题讨论】:

  • 您在两种情况下都有相同的str,并且您声称输出不同?
  • 但如果最后那个后面没有任何字母根据它即兴提出问题。
  • 不,第一个是“ABthatCDthatBHthatIOthatoo”,第二个是“ABthatCDthatBHthatIOthat”@pedromss

标签: java split-function


【解决方案1】:

试试这个

String fullStr = "ABthatCDthatBHthatIOthatoo";
String that= "that";
System.out.println(StringUtils.countMatches(fullStr, that));

使用来自apache common lang的StringUtils,这个https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.170

【讨论】:

【解决方案2】:

您可以为最终的“空”令牌指定一个限制

System.out.println(str.split("that", -1).length-1);

【讨论】:

  • 请解释将-1放在这里的原因,(“那个”,-1)@Reimeus
  • 所有解释都在javadoc如果n是非正数,那么该模式将被应用尽可能多的次数并且数组可以有任意长度 即不要丢弃空令牌
【解决方案3】:

使用 lastIndexOf() 找出子字符串“that”的位置,如果它位于字符串的最后位置,则将 cout 增加 1。

【讨论】:

  • indexOf() 返回第一次出现的索引。
【解决方案4】:

str.split("that").length 不计算 'that's 的数量。它计算 中间有“that”的单词数

例如-

class test
{
 public static void main(String args[]) 
 {
     String s="Hi?bye?hello?goodDay";
     System.out.println(s.split("?").length); 
 }
}

这将返回 4,即用“?”分隔的单词数。 如果返回length-1,在这种情况下,它会返回3,这是问号个数的正确计数。

但是,如果字符串是:“Hi????bye????hello?goodDay??”; ?

即使在这种情况下,str.split("?").length-1 也会返回 3,这是问号数的错误计数。

真正的功能 str.split("that //or anything") 是创建一个字符串数组,其中所有的字符/单词都用'that'分隔(在这种情况下)。 split() 函数返回一个字符串数组

所以,上面的 str.split("?") 实际上会返回一个字符串数组:{"Hi,bye,hello,goodDay"}

str.split("?").length 只返回数组的长度,其中 str 中的所有单词都用 '?' 分隔.

str.split("that").length 只返回数组的长度,其中 str 中的所有单词都由 'that' 分隔。

这是我解决问题的链接link

如果您有任何疑问,请告诉我。

【讨论】:

    【解决方案5】:

    我希望这会有所帮助

    public static void main(String[] args) throws Exception 
    
    
    {   int count = 0;
            String str = "ABthatCDthatBHthatIOthat"; 
            StringBuffer sc = new StringBuffer(str);
    
        while(str.contains("that")){
    
            int aa = str.indexOf("that");
            count++;
            sc = sc.delete(aa, aa+3);
            str = sc.toString();
    
    
        }
    
        System.out.println("count is:"+count);
    
    
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多