繁体   English   中英

计算文本文件中的字符数

[英]Counting the number of characters from a text file

我目前有以下代码:

public class Count {

    public static void countChar() throws FileNotFoundException {
        Scanner scannerFile = null;

        try {
            scannerFile = new Scanner(new File("file"));
        } catch (FileNotFoundException e) {
        }

        int starNumber = 0; // number of *'s

        while (scannerFile.hasNext()) {
            String character = scannerFile.next();
            int index =0;
            char star = '*';
            while(index<character.length()) {

                if(character.charAt(index)==star){
                    starNumber++;
                }
                index++;
            }
            System.out.println(starNumber);
        }
    }

我试图找出*在文本文件中出现了多少次。 例如,给定一个包含Hi * My * name *的文本文件

该方法应返回3

当前发生的是上述示例,该方法将返回:

0 1 1 2 2 3

提前致谢。

使用Apache commons-io将文件读入字符串

String org.apache.commons.io.FileUtils.readFileToString(File file);

然后,使用Apache commons-lang计算*的匹配数:

int org.apache.commons.lang.StringUtils.countMatches(String str, String sub)

结果:

int count = StringUtils.countMatches(FileUtils.readFileToString(file), "*");
int countStars(String fileName) throws IOException {
    FileReader fileReader = new FileReader(fileName);
    char[] cbuf = new char[1];
    int n = 0;

    while(fileReader.read(cbuf)) {
        if(cbuf[0] == '*') {
            n++;
        }
    }
    fileReader.close();
    return n;
}

您的方法中的所有内容都可以正常工作,只不过您可以按行打印计数:

    while (scannerFile.hasNext()) {
        String character = scannerFile.next();
        int index =0;
        char star = '*';
        while(index<character.length()) {

            if(character.charAt(index)==star){
                starNumber++;
            }
            index++;
        }
        /* PRINTS the result for each line!!! */
        System.out.println(starNumber);
    }

在这一点上,我将坚持使用Java库,然后在您更加熟悉核心Java API时使用其他库(例如commons库)。 这不在我的脑海中,可能需要进行调整才能运行。

StringBuilder sb = new StringBuilder();
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);

String s = br.readLine();
while (s != null)
{
  sb.append(s);
  s = br.readLine();
}
br.close(); // this closes the underlying reader so no need for fr.close()

String fileAsStr = sb.toString();
int count = 0;
int idx = fileAsStr('*')
while (idx > -1)
{
  count++;
  idx = fileAsStr('*', idx+1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM