如何在Java中统计文本文件中的括号和花括号?

3

我正在尝试计算程序在文本文档中找到的子字符串数量。文本文档:

# Data Value 0:
dataValue(0) {
  x: -3
  y: +9
  width: 68
  height: 25
}

在我的程序中,我试图打印'dataValue('出现的次数。但是我在使用括号时遇到了麻烦。在寻找解决方案时,我发现必须转义括号,这是正确的吗?然而,当我这样做时,程序会将其解释为'dataValue\('而不是'dataValue('。因此,没有找到匹配项。我能否避开这个问题?如果可以,任何帮助将不胜感激。

主要方法:

static String fileContent = "";

public static void main(String args[]) {

    fileContent = getFileContent("/Users/Rane/Desktop/search.txt");
    System.out.println(countSubstring(fileContent, "dataValue\\("));

}

getFileContent() 方法:

    public static String getFileContent(String filePath) {

    File textFile = new File(filePath);
    BufferedReader reader = null;

    String content = "";
    String currentLine = "";

    if(textFile.exists()) {
        try {

            reader = new BufferedReader(new FileReader(textFile));

            currentLine = reader.readLine();
            while(currentLine != null) {
                content = content + currentLine + "\n";;
                currentLine = reader.readLine();
            }

        } catch(Exception ext) {
            ext.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch(Exception ext) {
                ext.printStackTrace();
            }
        }

    } else {
        System.out.println("[WARNING]: Text file was not found at: " + filePath);
    }


    return content;
}

countSubstring() 方法:

static int countSubstring(String search, String substring) {

    int occurrences = 0;
    System.out.println(substring);

    search = search.toLowerCase();
    substring = substring.toLowerCase();

    while(search.indexOf(substring) > -1) {
        search = search.replaceFirst(substring, "");
        occurrences ++;
    }

    return occurrences;

}

控制台输出:

dataValue\(
0

提前感谢您!

2个回答

3
对于 indexOf 方法,您无需转义 (。与其他一些方法不同,indexOf 接受字符串作为参数,而不是正则表达式。
另一个需要注意的地方是,如果您只想计算数量,您需要更改此内容:
while(search.indexOf(substring) > -1) {
    search = search.replaceFirst(substring, "");
    occurrences ++;
}

To:

int index = -1;

while((index = search.indexOf(substring, ++index)) > -1) 
    occurances++;
< p > indexOf 方法可以返回指定子字符串的位置。我们使用的是带有“从哪里开始匹配”的重载版本。这样做是为了避免不断找到相同的元素,从而导致无限循环。


谢谢你的回答。我有一个快速的跟进问题。为什么需要一个起始位置?在我的原始代码中,如果找到了子字符串,我就替换它。这难道不会防止无限循环吗?再次感谢。 - Rane1011
2
起始位置用于避免命中先前的匹配项,这也可以通过从字符串中删除先前的匹配项来实现。问题在于,当您更改字符串时,您正在创建一个新的字符串。根据字符串的大小,此操作可能非常昂贵。 - npinti

1

那是因为你混用了搜索字符串:

  • indexOf()使用普通搜索字符串
  • replaceFirst()使用正则表达式

如果你只想提供一个普通字符串,可以使用Pattern.quote()将其引用为正则表达式。

更好的方法是不要浪费时间替换搜索字符串,只需继续搜索,使用indexOf()进行简单搜索字符串,或使用find()进行正则表达式搜索:

// Using indexOf() with a plain search string
int start = -1, count = 0;
while ((start = search.indexOf(substring, ++start)) != -1)
    count++;
return count;

// Using find() with a regular expression search string
Matcher m = Pattern.compile(substring).matcher(search);
int count = 0;
while (m.find())
    count++;
return count;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接