【问题标题】:Search for appearances of string inside text在文本中搜索字符串的外观
【发布时间】:2014-08-30 19:11:19
【问题描述】:

我有一个 .txt 文件,其中包含一些文本。

例如Hello, world

我想搜索整个文件并找出一个字符串有多少次出现以及它们的位置,例如上面文本中的“wo”有一个。该数字应放在编辑文本中。但是我只知道如何搜索特定的字符而不是整个文本,你能帮帮我吗?非常感谢

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);

【问题讨论】:

标签: java bufferedreader


【解决方案1】:
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】:

你可以使用类似的东西:

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);

在执行此操作之前,将“目标”字符串中的整个文本连接起来,或者如果您确定目标字符串不会出现在某行的末尾和下一行的开头,则为每一行执行前面的代码

【讨论】:

    【解决方案3】:

    如果你使用的是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());
        }
    }
    

    【讨论】:

      【解决方案4】:

      为简单起见,我会读一行并使用“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'是最好的方法。

      【讨论】:

        猜你喜欢
        • 2011-09-13
        • 2017-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-10
        • 1970-01-01
        相关资源
        最近更新 更多