我想計算程序在文本文檔中找到的子字符串的數量。文本文檔:如何在Java中的文本文件中計算括號和大括號?
# 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
在此先感謝!
謝謝您的回答。我剛剛有一個快速的後續問題。你爲什麼需要一個起始位置?在我最初的代碼中,如果找到了子字符串,我會替換它。這不妨礙無限循環?再次感謝。 – Rane1011
起始位置用於避免擊中以前的匹配,這也可以通過從字符串中移除前一匹配來實現。問題是,當你改變一個字符串時,你正在創建一個新的字符串。根據字符串的大小,此操作可能非常昂貴。 – npinti