2015-12-31 50 views
3

我想計算程序在文本文檔中找到的子字符串的數量。文本文檔:如何在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 

在此先感謝!

回答

3

對於indexOf,您不需要轉義(indexOf接受一個字符串作爲參數,而不是一個正則表達式不像其他一些方法。

另要注意,你需要改變這一點,如果你只是想算的東西:

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

要:

int index = -1; 

while((index = search.indexOf(substring, ++index)) > -1) 
    occurances++; 

indexOf產生所提供的串的位置。我們正在使用一個重載版本,它也從哪裏開始匹配。我們需要這樣做,以避免繼續找到相同的元素,從而使其成爲一個無限循環。

+0

謝謝您的回答。我剛剛有一個快速的後續問題。你爲什麼需要一個起始位置?在我最初的代碼中,如果找到了子字符串,我會替換它。這不妨礙無限循環?再次感謝。 – 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; 
相關問題