Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
文件中的Java计数特殊字符_Java_Loops_Search_Count_Char - Fatal编程技术网

文件中的Java计数特殊字符

文件中的Java计数特殊字符,java,loops,search,count,char,Java,Loops,Search,Count,Char,我需要计算文件中特定字符的数量。用户将指定字符,我只需要检查文件中有多少个字符 package assignmentoneqone; import java.util.Scanner; import java.io.FileReader; import java.io.File; import java.io.IOException; /** * * @author Hannes */ public class AssignmentOneQOne { /** * @p

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

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.");
                }                 
    }
}

用美丽的番石榴做这个。。。如果可以的话

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

打开你的文件,在一个while循环中逐行阅读

在while循环中,您可以计算一个字符,如:

int counter = 0;
char[] arr = line.toCharArray();

for (char c: arr){
    if (c == '<your char>' || c== '<YOUR CHAR UPPERCASE >')
      counter++;
}

如果您正在寻找oneliner:

System.out.println(myString.replaceAll("[^a]+", "").length());
注意:可能不是最快的。

行是您从文件中读取的内容。就像我说的:在while循环中逐行读取文本文件。
System.out.println(myString.replaceAll("[^a]+", "").length());