Java计数单词和字符

时间:2018-02-22 00:37:44

标签: java string text-files

我应该创建一个程序来计算文本文件中的单词数和平均字符数(不含空格)。我创建的程序我只有一个问题。我的字符计数器总数计算字符" - "和"。"在计算单词时,我不希望这种情况发生。目前,我计算了300个字符。有四个"。"和一个" - "应该从柜台中删除所以我可以得到295的总值。我尝试使用char但我遇到了不允许我将字符串与char进行比较的错误。我的朋友推荐我比较我应该尝试使用一种方法来比较char和Unicode,但我不知道如何开始编码。

int main(void)
{    
    char menu[200] = "1 - run first task\n2 - run se...";
    char x = 0;

    while (1)
    {
        puts(menu);
        x = getch();

        switch (x)
        {
        case ('1'):
            task1();
            break;

        case('2'):
            task2();
            break;

        case('c'):
            system("cls");
            break;

        case('x'):
            break;

        default:
            printf("Please choose a valid option!!");
            break;
       }
    }   
}

3 个答案:

答案 0 :(得分:1)

在做之前

String[] words = sourceCode.split(" ");

使用replace

删除所有不需要的字符

e.g。

sourceCode = sourceCode.replace ("-", "").replace (".", "");
String[] words = sourceCode.split(" ");

答案 1 :(得分:0)

或者你可以使用全部3个字符“”,“。”和“;”在我想的溢出中。

答案 2 :(得分:0)

以下是您问题的答案......

public static int numberOfWords(File someFile) {
    int num=0;
    try {
        String line=null;
        FileReader filereader=new FileReader(someFile);
        try (BufferedReader bf = new BufferedReader(filereader)) {
            while((line=bf.readLine()) !=null) {
                if (!line.equals("\n")) {
                    if (line.contains(" ") {
                        String[] l=line.split(" ");
                        num=num+l.length;
                    } else {
                        num++;
                    }
                }
            }
        }
    } catch (IOException e) {}
    return num;
}

public static int numberOfChars(File someFile) {
    int num=0;
    try {
        String line=null;
        FileReader filereader=new FileReader(someFile);
        try (BufferedReader bf = new BufferedReader(filereader)) {
            while((line=bf.readLine()) !=null) {
                if (!line.equals("\n")) {
                    if (line.contains(" ") {
                        String[] l=line.split(" ");
                        for (String s : l) {
                            s=replaceAllString(s, "-", "");
                            s=replaceAllString(s, ".", "");
                            String[] sp=s.split("");
                            num=num+sp.length;
                        }
                    } else {
                        line=replaceAllString(line, "-", "");
                        line=replaceAllString(line, ".", "");
                        String[] sp=line.split("");
                        num=num+sp.length;
                    }
                }
            }
        }
    } catch (IOException e) {}
    return num;
}

public static String replaceAllString(String s, String c, String d){
    String temp = s.replace(c ,d);
    return temp;
}