(Java)在句子中计算字母? [英] (Java) Counting letters in a sentence?

查看:74
本文介绍了(Java)在句子中计算字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码:

char[] array = new char[26] ;

    int index = 0 ;
    int letter = 0 ;
    int countA = 0 ;

    String sentence = "Once upon a time..." ;

    if(sentence.contains("."))
    {
        String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
        String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;
        char[] count = new char[sentenceFinal.length()] ;
        for (char c = 'a'; c <= 'z'; c++) 
        {
            array[index++] = c ;
            for(int i = 0; i < sentenceFinal.length(); i++)
            {
                if(sentenceFinal.charAt(i) == c)
                    count[letter++] = c ; 
                //if(sentenceFinal.charAt(i) == 'a')    
                    //countA++ ;   
            }

        }
        String result = new String(count) ; // Convert to a string.
        System.out.println("\n" + result) ;

        System.out.println("\nTotal number of letters is " + result.length()) ;
        System.out.println(countA) ;
    }
    else
    {
       System.out.println("You forgot a period. Try again.") ;
    }

我无法计算a,b,c等的数量在给定的句子中。我有一种方法可以做到,而这就是这部分

I am having trouble counting how many a's, b's, c's, etc. are in a given sentence. There is one way I can do it and it is this part

//if(sentenceFinal.charAt(i) == 'a')    
                //countA++ ;

我可以一直创建到z。有没有更有效的方法?

which I can just create all the way to z. Is there a more efficient way?

注意:不使用Hashmap或任何其他高级技术。

Note: No using Hashmap or any other advance techniques.

推荐答案

不需要消除空格。

int countOfLetters = 0 ;
String sentence = "Once upon a time..." ;
sentence = sentence.toLowerCase();
int[] countOfAlphabets = new int[26];
for (int i = 0; i < sentence.length(); i++) {
    if (sentence.charAt(i) >= 'a' && sentence.charAt(i) <= 'z') {
        countOfAlphabets[sentence.charAt(i) - 97]++;
        countOfLetters++;
    }
}

因此, countOfLetters 将给您字母总数。
如果您要进行个人计数,例如,假设您要计数'c'

So, countOfLetters will give you the total count of letters. If you want individual count, suppose for example, you want count of 'c',

您可以通过访问 countOfAlphabets 数组,例如 countOfAlphabets ['c'-97] (97是'a'的ASCII值)

You can get it by accessing countOfAlphabets array like countOfAlphabets['c' - 97] (97 being the ASCII value of 'a')

这篇关于(Java)在句子中计算字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆