這裏是我的代碼:找到所有字符串「中的」在.txt文件
// Import io so we can use file objects
import java.io.*;
public class SearchThe {
public static void main(String args[]) {
try {
String stringSearch = "the";
// Open the file c:\test.txt as a buffered reader
BufferedReader bf = new BufferedReader(new FileReader("test.txt"));
// Start a line count and declare a string to hold our current line.
int linecount = 0;
String line;
// Let the user know what we are searching for
System.out.println("Searching for " + stringSearch + " in file...");
// Loop through each line, stashing the line into our line variable.
while ((line = bf.readLine()) != null){
// Increment the count and find the index of the word
linecount++;
int indexfound = line.indexOf(stringSearch);
// If greater than -1, means we found the word
if (indexfound > -1) {
System.out.println("Word was found at position " + indexfound + " on line " + linecount);
}
}
// Close the file after done searching
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
我想找到一些字「的」在test.txt文件。問題是當我找到第一個「the」,我的程序停止發現更多。
而當某些詞像「然後」我的程序明白它是字「的」。
你有沒有考慮過使用Java的正則表達式包(java.util.regex)? – GobiasKoffi 2010-09-13 04:39:33
你可以在這裏找到一些有用的例子。http://java.sun.com/developer/technicalArticles/releases/1.4regex/ – Emil 2010-09-13 05:01:44