本问题已经有最佳答案,请猛点这里访问。
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",第二个是" ABthatCDthatBHthatIOthatoo" @pedromss
您可以指定一个限制来说明最终的"空"令牌
System.out.println(str.split("that", -1).length-1);
stackoverflow.com/a/770069/1746118
请在此处说明放置-1的原因,(" that",-1)@Reimeus
javadoc中的所有解释如果n为非正数,则该模式将被尽可能多地应用,并且数组可以具有任意长度,即不要丢弃空令牌
str.split("that").length doesn't count the number of 'that's . It counts the
number of words that have 'that' in between them
例如-
class test
{
public static void main(String args[])
{
String s="Hi?bye?hello?goodDay";
System.out.println(s.split("?").length);
}
}
这将是4,即用"?"分隔的单词数。
如果返回length-1,在这种情况下,它将返回3,这是问号数量的正确计数。
But, what if the String is :"Hi????bye????hello?goodDay??"; ?
即使在这种情况下,str.split("?")。length-1也将返回3,这是对问号数量的错误计数。
str.split(" that // or any")的实际功能是创建一个String数组,其中所有这些字符/单词都用'that'分隔(在本例中)。split()函数返回一个String数组。
因此,上面的str.split("?")实际上将返回一个String数组:{" Hi,bye,hello,goodDay"}
str.split("?")。length除了数组的长度外什么都不返回,该数组的所有单词均以'?'分隔。 。
str.split(" that")。length只返回数组的长度,该数组的长度是str中所有单词之间用'that'分隔的长度。
这是我的问题链接解决方案链接
如果您有任何疑问,请告诉我。
我希望这会有所帮助
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);
}
使用lastIndexOf()找出子字符串" that"的位置,如果它在字符串的最后位置,则将cout增加答案的1。
indexOf()返回第一次出现的索引。
尝试这个
String fullStr ="ABthatCDthatBHthatIOthatoo";
String that="that";
System.out.println(StringUtils.countMatches(fullStr, that));
使用来自Apache通用语言的StringUtils,这是https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/src-html/org/apache/commons/lang/StringUtils.html#line.170
您可能想详细说明StringUtils是什么,它不能自我解释。
使用来自Apache公共语言的StringUtils,这是commons.apache.org/proper/commons-lang/javadocs/api-2.6/
更新您的答案而不是评论中的内容。