如果我想比较一个单词用于另一个单词的数量,我该怎么做?
不会是str.contains("cat") > str.contains("dog")
例如:
if(str.contains("cat") == str.contains("dog")){
System.out.println("true");
}
else
system.out.print("false");
如果猫和狗看起来相同的次数,这将假设打印为真。但显然它没有,我还有什么需要检查?
答案 0 :(得分:1)
String#contains()
将返回true,这是出于性能原因而完成的。因此,str.contains("cat") == str.contains("dog")
如果发现猫和狗都不依赖于它们的发现频率,那将是真实的。
你可以做的是使用2个正则表达式并检查匹配数:
int countWords(String input, String word ) {
Pattern p = Pattern.compile( "\\b" + word + "\\b" );
int count = 0;
Matcher m = p.matcher( input );
while( m.find() ) {
count++;
}
return count;
}
用法:
String str = "dog eats dog but cat eats hotdog";
System.out.println("dogs: " + countWords( str, "dog"));
System.out.println("cats: " + countWords( str, "cat"));
输出:
dogs: 2
cats: 1
答案 1 :(得分:1)
要计算另一个String中String的出现次数,请创建一个函数(extracted from here):
“拆分与统计”方法:
public class CountSubstring {
public static int countSubstring(String subStr, String str){
// the result of split() will contain one more element than the delimiter
// the "-1" second argument makes it not discard trailing empty strings
return str.split(Pattern.quote(subStr), -1).length - 1;
}
“删除并计算差异”方法:
public static int countSubstring(String subStr, String str){
return (str.length() - str.replace(subStr, "").length()) / subStr.length();
}
然后你只需要比较:
return countSubstring("dog", phrase) > countSubstring("cat", phrase);
其他信息
要比较字符串,请使用String::equals或String::equalsIgnoreCase,如果您不是uppercase
和lowercase
。
string1.equals(string2);
string1.equalsIgnoreCase(string2);
要查找另一个字符串中字符串的出现次数,请使用indexOf
string1.indexOf(string2, index);
要查看字符串是否包含其他字符串,请使用contains
string1.contains(string2);
答案 2 :(得分:0)
您的问题有很多可能的解决方案。我不会向您展示完整的解决方案,但会尽力指导您。以下是一些:
split
根据空格的字符串,迭代结果数组并在匹配您正在寻找的字符串时递增计数器。
Java 8 Stream tools有无数的方法,你可以把结果放在一行。
答案 3 :(得分:0)
你可以通过以下方式获得狗的计数
index = -1;
dogcount = 0;
do {
index = str.indexOf("dog",index+1);
if(index > -1)
dogcount++;
}while(index == -1);
同样得猫数
答案 4 :(得分:0)
使用Apache Commons StringUtils.CountMatches: - 计算另一个String中出现的次数