我正在尝试计算程序在文本文档中找到的子字符串数量。文本文档:
# 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
提前感谢您!