0

我正在寻找解析输入String,并且当我这样做时,我想检查每个单词的出现次数,同时删除所有非字母字符。

例如:

String str = "test man `xy KA XY test!.. KA kA TeST man poqw``e TES`T"
String s = line.replaceAll("[^\\p{L}\\p{N}\\ ]", "");
String[] werd = alphaLine.split(" ");

for(int i=0; i<werd.size(); i++) {
     if(werd[i].toLowerCase().equals("test")) {
         testcounter++;
     elseif(werd[i].toLowerCase().equals("ka")) {
         kacounter++;
     etc..

我将检查很长String的s,并将检查许多目标Strings(在这个例子中),katest试图看看我是否可以一次执行这段代码,因为现在看来 for .replaceAll(), .split(), 然后for 循环我正在经历所有的Strings 3 次,当它可以完成一次时。

4

1 回答 1

0

不确定我是否在同一页面上,但听起来您在问如何在搜索单词时减少查找次数。如果您有大量搜索词,这可能不是最好的方法,但应该为较小的列表提供每个词的出现次数。

Map<String, Integer> occurrences = new HashMap<String, Integer>();
List<String> words = new ArrayList<String>();
words.add("foo");
words.add("bar");

//build regex - note: if this is done within an outer loop, then you should consider using StringBuilder instead
//The \b in regex is a word boundary
String regex = "\\b(";
for(int i = 0; i < words.size(); i++) {
    //add word to regex
    regex += (0 == i ? "" : "|") + words.get(i);

    //initial occurrences
    occurrences.add(words.get(i), 0);
}
regex += ")\\b";
Pattern patt = Pattern.compile(regex);
Matcher matcher = patt.matcher(search_string);

//check for matches
while (matcher.find()) {
    String key = matcher.group();
    int numOccurs = occurrences.get(key) + 1;
    occurrences.put(key, numOccurs);
}

编辑:这是假设您在此之前处理非字母要求

于 2013-03-17T17:39:15.433 回答