【发布时间】:2012-03-26 06:57:53
【问题描述】:
鉴于以下情况:
String s = "The The The the the the";
如何找出字符串 s 中有多少个“The”?
s.matches("The") 只会告诉我是否至少有一个。
s.contains("The") 也一样。
有什么简单的方法吗?
【问题讨论】:
鉴于以下情况:
String s = "The The The the the the";
如何找出字符串 s 中有多少个“The”?
s.matches("The") 只会告诉我是否至少有一个。
s.contains("The") 也一样。
有什么简单的方法吗?
【问题讨论】:
据我所知,Matcher.find() 方法试图找到与模式匹配的输入序列的下一个子序列。这意味着您可以多次调用此方法来遍历匹配项:
int count = 0;
while (matcher.find()) {
count++;
}
你应该使用 Matcher.start() 和 Matcher.end() 来检索匹配的子序列。
【讨论】:
您可以使用indexOf(str, count)
int count = 0;
String s = "The The The the the the";
String match = "The";
int searchStart = 0;
while ((searchStart = s.indexOf(match, searchStart)) != -1)
{
count++;
searchStart+= match.length();
}
【讨论】:
searchStart += match.length。
match 字符串的长度为 1000 个符号,那么每次迭代都必须浪费 1000 个 cpu 周期来重新比较已经完成的操作。
试试这个:
String test = "The The The the the the";
System.out.println(test.split("The").length);
【讨论】:
String.split 的怪异行为,这不一定有效。 String test = "The The The the the theTheTheThe"; System.out.println(test.split("The").length); 打印出4,这肯定不是正确答案。 String.split 在尾随分隔符上有奇怪的行为,如果您在搜索字符串的末尾出现搜索字符串,这将使其不起作用。
您可以使用 s.indexOf("The", index);,如果它返回某个索引,则增加 count 和 index > 也让它成为一个循环,直到找不到索引。
注意:最初 index 的值为 0
【讨论】:
简单地拆分要统计的单词上的字符串。
String text = "the the water the the";
System.out.println(text.split("the", -1).length -1);
另外,如果你当前使用的是 apache commons lang,你可以使用 StringUtils 中的 count 函数
String text = "the the water the the";
int count = StringUtils.countMatches(text, "the");
System.out.println("count is " + count);
但是,不要只为那个有点矫枉过正的功能引入它:)
【讨论】:
String s = "The The The The The sdfadsfdas";
List<String> list = Arrays.asList(s.split(" "));
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
System.out.println(key + ": " + Collections.frequency(list, key));
}
【讨论】: