我有一个字符串数组
A=["hello", "you"]
我有一个字符串,比如说
s="hello, hello you are so wonderful"
我需要计算A
中来自s
的字符串出现次数。
在这种情况下,出现次数为3(2 "hello"
,1 "you"
)。
如何有效地做到这一点? (A
可能包含大量单词,而s
可能在实践中很长)
答案 0 :(得分:2)
尝试:
Map<String, Integer> wordCount = new HashMap<>();
for(String a : dictionnary) {
wordCount.put(a, 0);
}
for(String s : text.split("\\s+")) {
Integer count = wordCount.get(s);
if(count != null) {
wordCount.put(s, count + 1);
}
}
答案 1 :(得分:1)
int count =0;
for(int i=0;i<A.length;i++)
{
count = count + s.split(A[i],-1).length - 1;
}
工作Ideone:http://ideone.com/Z9K3JX
答案 2 :(得分:1)
public void countMatches() {
String[] A = {"hello", "you"};
String s = "hello, hello you are so wonderful";
String patternString = "(" + StringUtils.join(A, "|") + ")";
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(s);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);
}
请注意,StringUtils来自apache commons。如果你不想包含和使用额外的jar,你可以使用for循环来构造该字符串。
答案 3 :(得分:1)
HashSet<String> searchWords = new HashSet<String>();
for(String a : dictionary) {
searchWords.add(a);
}
int count = 0;
for(String s : input.split("[ ,]")) {
if(searchWords.contains(s)) {
count++;
}
}
答案 4 :(得分:0)
这是输出完全正常的方法:)
public static void main(String[] args) {
String[] A={"hello", "you"};
String s= "hello, hello you are so wonderful";
int[] count = new int[A.length];
for (int i = 0; i < A.length; i++) {
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
}
for (int i = 0; i < count.length; i++) {
System.out.println(A[i] + ": " + count[i]);
}
}
这条线做什么?
count[i] = (s.length() - s.replaceAll(A[i], "").length())/A[i].length();
此部分s.replaceAll(A[i], "")
将所有“hello”更改为文本中的空“”字符串。
所以我考虑了所有内容的长度s.length()
我从中减去了没有该词s.replaceAll(A[i], "").length()
的同一个字符串的长度,并将其除以该字/A[i].length()
的长度
此示例的示例输出:
hello: 2
you: 1
答案 5 :(得分:0)
您可以使用String Tokenizer
做这样的事情:
A = ["hello", "you"];
s = "hello, hello you are so wonderful";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreElements()) {
for (String i: A) {
if(st.nextToken() == i){
//You can keep going from here
}
}
}
答案 6 :(得分:0)
这就是我提出的:
它不会创建任何新对象。它使用String.indexOf(String, int)
,跟踪当前索引,并增加出现次数。
public class SearchWordCount {
public static final void main(String[] ignored) {
String[] searchWords = {"hello", "you"};
String input = "hello, hello you are so wonderful";
for(int i = 0; i < searchWords.length; i++) {
String searchWord = searchWords[i];
System.out.print(searchWord + ": ");
int foundCount = 0;
int currIdx = 0;
while(currIdx != -1) {
currIdx = input.indexOf(searchWord, currIdx);
if(currIdx != -1) {
foundCount++;
currIdx += searchWord.length();
} else {
currIdx = -1;
}
}
System.out.println(foundCount);
}
}
}
输出:
hello: 2
you: 1