在文本中搜索字符串的外观

时间:2014-07-09 16:29:22

标签: java bufferedreader

我有一个.txt文件,里面有一些文字。

例如Hello, world

我想搜索整个文件,找出字符串有多少个外观以及它们的位置,例如" wo"在上面的文字有一个。该号码应放在edittext中。但是我只知道如何搜索特定的字符而不是全文,你能帮帮我吗?非常感谢

BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
int ch;
char charToSearch='a';
int counter=0;
while((ch=reader.read()) != -1) {
    if(charToSearch == (char)ch) {
        counter++;
    }
};
reader.close();

System.out.println(counter);

4 个答案:

答案 0 :(得分:0)

您可以使用以下内容:

int nFound = 0;
String target = ".............Your long text..................";
String search = "find this"
int startIndex = 0
do
{
    int index = target.indexOf(search, startIndex);
    if(index !=-1)
    {
        // Found
        nFound++;

        // Here you have the index variable, which says you the position of the found match
        /*  DO your job  */

        /* Update the index to start the search again on the rest of the string, until no matches are found*/
        startIndex = index+1;
    }
    else
        break;


}while(true);

在此之前,将整个文本连接到" target"如果您确定目标字符串不会出现在某行的末尾并且下一行的开头

,则为每行代码字符串或dexecute

答案 1 :(得分:0)

public static int countWord(String word, FileInputStream fis) {
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    String readLine = "";
    int count = 0;
    try {
        while ((readLine = in.readLine()) != null) {
            String[] words = readLine.split(" ");
            for (String s : words) {
                if (s.contains(word))
                    count++;
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return count;
}

答案 2 :(得分:0)

如果您使用的是Java 7,那么根据this,您可以获得包含整个文件的String:

String text = new String(Files.readAllBytes(Paths.get("file")), StandardCharsets.UTF_8);

然后,你可以这样做:

public void print(String word)
{
    String tempStr = null;
    int count = 0;
    while (tempStr.indexOf(word) != -1)
    {
        System.out.printf("Position: %d, Count: %d\r\n", tempStr.indexOf(word), ++count);
        tempStr = tempStr.substring(tempStr.indexOf(word) + word.length());
    }
}

答案 3 :(得分:0)

为简单起见,我会读一行并使用“string.split(String regex)”。

while(readLine) {
  String[] str = readLine.split(regex);
  //you can tell based on the array, how many matches and their position. 
}

您还可以使用util.Scanner或regex.Pattern。

但如果你正在寻找表现,我认为'string.indexOf'是最好的方法。

相关问题