计算输入文件中的字符出现次数

时间:2016-08-09 11:31:51

标签: java

我的程序提示用户输入特定的字母和文件名,然后打印出输入文件中参数字母的出现次数。

我编写的代码:

public class CharCount {
    public static void main(String[] args)  {
        Scanner inp= new Scanner(System.in);
        String str;
        char ch;
        int count=0;

        System.out.println("Enter a letter: ");
        str=inp.nextLine();
        while(str.length()>0)
        {
            ch=str.charAt(0);
            int i=0;

            while (i < str.length() && str.charAt(i) == ch)
            {
                count++;
                i++;
            }
            str = str.substring(count);
            System.out.println(ch + " appears " + count + " in" );
        }
    }
}

我得到了这个输出

Enter a letter:
e appears 1 in

但我应该得到这个输出

Enter a letter: Enter a filename: e appears 58 times in input.txt

任何帮助/建议都会很棒:)

3 个答案:

答案 0 :(得分:1)

使用Java 8,您可以依靠流来为您完成工作。

String sampleText = "Lorem ipsum";
Character letter = 'e';
long count = sampleText.chars().filter(c -> c == letter).count();
System.out.println(count);

答案 1 :(得分:1)

让我们开始帮助:

   // Ask letter:
   System.out.println("Enter a letter: ");
   String str = inp.nextLine();
   while (str.isEmpty()) {
       System.out.println("Enter a letter:");
       str = inp.nextLine();
   }
   char letter = str.charAt(0);

   // Ask file name:
   System.out.println("Enter file name:");
   String fileName = inp.nextLine();
   while (fileName.isEmpty()) {
       System.out.println("Enter file name:");
       fileName = tnp.nextLine();
   }

   // Process file:
   //Scanner textInp = new Scanner(new File(fileName)); // Either old style
   Scanner textInp = new Scanner(Paths.get(fileName)); // Or new style
   while (textInp.hasNextLine()) {
       String line = textInp.nextLine();
       ...
   }

答案 2 :(得分:0)

你可以使用正则表达式。

进口:

import java.util.regex.*;

Ex用法:

String input = "abcaa a";
String letter = "a";
Pattern p = Pattern.compile(letter, Pattern.CASE_INSENSITIVE + Pattern.MULTILINE);
Matcher m = p.matcher(input);

int i = 0;
while(m.find()){
  i++;
}
System.out.println(i); // 4 = # of occurrences of "a". 
相关问题