javaarrayscharcounting

(Java) Counting letters in a sentence?


The following is my code:

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

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++ ;

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

Note: No using Hashmap or any other advance techniques.


Solution

  • There is no need of eliminating spaces. This is just additional work you're doing.

    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++;
        }
    }
    

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

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