有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java字符串解析和求和

我希望解析一个输入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,并将检查许多目标Stringkatest),并试图看看我是否可以在一次通过中执行此代码,因为现在似乎对于.replaceAll().split(),然后是for循环,我将通过所有String的3次,什么时候可以做一次


共 (1) 个答案

  1. # 1 楼答案

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

    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);
    }
    

    编辑:这是假设您在这一点之前处理了非alphanum需求