【问题标题】:Java count spesific char in fileJava计算文件中的特定字符
【发布时间】:2014-03-10 11:38:40
【问题描述】:

我需要计算文件中特定字符的数量。用户将指定我只需要检查文件中有多少个字符的字符。

package assignmentoneqone;
import java.util.Scanner;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;

/**
 *
 * @author Hannes
 */
public class AssignmentOneQOne {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner kb = new Scanner(System.in);

        String fileLoc;
        String userChar;

        //User specify the file and character

        System.out.println("Enter the file name");
        fileLoc = kb.nextLine();
        System.out.println("Enter a character");
        userChar = kb.nextLine();

        File file = new File(fileLoc);
        try
        {
        FileReader fw = new FileReader(file);

这是我应该搜索字符的地方。

        }
        catch(IOException e)
                {
                System.out.println("The file does not exist.");
                }                 
    }
}

【问题讨论】:

    标签: java loops search count char


    【解决方案1】:

    为此使用漂亮的番石榴......(如果可以的话)

            int result = CharMatcher.is('t').countIn("test"); //of course for each line instead of 'test'
        System.out.println(result);
    

    【讨论】:

      【解决方案2】:

      打开您的文件,在 while 循环中逐行读取(谷歌如何)。

      在您的 while 循环中,您可以计算如下字符:

      int counter = 0;
      char[] arr = line.toCharArray();
      
      for (char c: arr){
          if (c == '<your char>' || c== '<YOUR CHAR UPPERCASE >')
            counter++;
      }
      

      【讨论】:

      【解决方案3】:
              file FileReader fw = new FileReader(file);
              int a = 0;
              int charCount = 0;
              while(( a = fw.read())!= -1)
              {
                  byte b = (byte) a;
                  if(b == 32 || b == 10) // Ascii value of space and enter
                  {
                      continue;
                  }
                  charCount++;
              }
              System.out.println("The character count is "+charCount);
      

      【讨论】:

        【解决方案4】:

        如果您正在寻找单线:

        System.out.println(myString.replaceAll("[^a]+", "").length());
        

        注意:可能不是最快的。

        【讨论】:

          猜你喜欢
          • 2012-06-07
          • 1970-01-01
          • 2015-06-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-30
          • 2015-07-05
          • 1970-01-01
          相关资源
          最近更新 更多