Đây là mã của tôi:Tìm tất cả các chuỗi "the" trong tập tin .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());
}
}
}
tôi muốn tìm một số từ "the" trong test.txt tập tin. Vấn đề là khi tôi tìm thấy "số" đầu tiên, chương trình của tôi ngừng tìm kiếm thêm.
Và khi một số từ như "thì" chương trình của tôi hiểu nó là từ "số".
Bạn đã cân nhắc sử dụng gói regex của Java (java.util.regex) chưa? – GobiasKoffi
Bạn có thể tìm thấy một số ví dụ hữu ích tại đây.http: //java.sun.com/developer/technicalArticles/releases/1.4regex/ – Emil