(Java) Counting letters in a sentence?

 ̄綄美尐妖づ 提交于 2019-12-24 10:44:56

问题


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.


回答1:


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')




回答2:


Use an int array letterCounts that will store the counts for each letter. Assuming the case of the letters can be ignored, the length of the letterCounts array will be 26.

Iterate over the string's characters and update the corresponding integer in the array. Use its ASCII value to find the corresponding index, as follows.

letterCounts[c - 97]++

97 is the ASCII value of 'a', whose count needs to be stored at index 0.

In this way, subtracting 97 from the character's ASCII value will give the corresponding index for that character.

Note: This is assuming that you want to store the counts for lowercase letters.




回答3:


Pretty fiddly without using maps, but this will count all characters in a string.

You might want to modify to exclude things like spaces etc.

public class Main {

    public static void main(String[] args) {
        String sentence = "Once upon a time...";

        // Create an array of size 256 ASCII_SIZE
        int count[] = new int[256];
        int length = sentence.length();

        // Initialize count array index
        for (int i = 0; i < length; i++)
            count[sentence.charAt(i)]++;

        // Create an array of given String size
        char chars[] = new char[sentence.length()];
        for (int i = 0; i < length; i++) {
            chars[i] = sentence.charAt(i);
            int find = 0;
            for (int j = 0; j <= i; j++) {

                // If any matches found
                if (sentence.charAt(i) == chars[j])
                    find++;
            }

            if (find == 1) {
               System.out.println("Occurrence of " + sentence.charAt(i) + " is:" + count[sentence.charAt(i)]);

            }
        }
    }
}

Which outputs:

Occurrence of O is:1
Occurrence of n is:2
Occurrence of c is:1
Occurrence of e is:2
Occurrence of   is:3
Occurrence of u is:1
Occurrence of p is:1
Occurrence of o is:1
Occurrence of a is:1
Occurrence of t is:1
Occurrence of i is:1
Occurrence of m is:1
Occurrence of . is:3



回答4:


Check Below code You can have a 26 length array and index will increment according to the presence of the alphabet.

public void getResult(){

        int [] charCount = new int [26];
        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[] sentenceCharArray = sentenceFinal.toCharArray();
            //char a = 97;
            for (int i = 0; i <sentenceCharArray.length ; i++) {
                int index = sentenceCharArray[i] - 97 ;
                if(index >= 0 && index <= 26) {
                    charCount[index] += 1;
                }
            }


            System.out.print("Result : ");

            for (int i = 0; i < charCount.length ; i++) {
                System.out.print(charCount [i]+" , ");
            }


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



回答5:


Since there are 26 letters in the US alphabet, you can use an int[] with a size of 26

int[] letterCount = new int[26];

to hold the count of each letter where index 0 represents 'a', 1 represents 'b', etc...

As you traverse through the sentence, check if the character you're on is a letter, Character.isLetter(), then increment the element in the array that represents the letter.

letterCount[letter - 'a']++;

We subtract 'a' from the letter to give us the correct index.

Code Sample

package stackoverflow;

public class Question {

    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog.";
        int[] letterCount = new int[26];
        if (sentence.contains(".")) {
            // toLowerCase() the sentence since we count upper and lowercase as the same
            for (char letter : sentence.toLowerCase().toCharArray()) {
                if (Character.isLetter(letter)) {
                    letterCount[letter - 'a']++;
                }
            }

            // Display the count of each letter that was found
            int sumOfLetters = 0;
            for (int i = 0; i < letterCount.length; i++) {
                int count = letterCount[i];
                if (count > 0) {
                    System.out.println((char)(i + 'a') + " occurs " + count + " times");
                    sumOfLetters += count;
                }
            }

            System.out.println("Total number of letters is " + sumOfLetters);
        } else {
            System.out.println("You forgot a period.  Try again.");
        }
    }
}

Result

a occurs 1 times
b occurs 1 times
c occurs 1 times
d occurs 1 times
e occurs 3 times
f occurs 1 times
g occurs 1 times
h occurs 2 times
i occurs 1 times
j occurs 1 times
k occurs 1 times
l occurs 1 times
m occurs 1 times
n occurs 1 times
o occurs 4 times
p occurs 1 times
q occurs 1 times
r occurs 2 times
s occurs 1 times
t occurs 2 times
u occurs 2 times
v occurs 1 times
w occurs 1 times
x occurs 1 times
y occurs 1 times
z occurs 1 times
Total number of letters is 35

Rebuttal Question

What is wrong with using Java 8 and using the chars() of a String? With it, you can accomplish the same thing with less code. For the total number of letters, we just use String.replaceAll() and remove all non-letters from the String with the pattern [^A-Za-z]and use the length() of the result.

package stackoverflow;

import java.util.function.Function;
import java.util.stream.Collectors;

public class Question {

    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog.";

        System.out.println(sentence.toLowerCase().chars()
            // Change the IntStream to a stream of Characters
            .mapToObj(c -> (char)c)
            // Filter out non lower case letters
            .filter(c -> 'a' <= c && c <= 'z')
            // Collect up the letters and count them
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())));

        System.out.println("Total letter count is " + sentence.replaceAll("[^A-Za-z]", "").length());               
    }
}

Result

{a=1, b=1, c=1, d=1, e=3, f=1, g=1, h=2, i=1, j=1, k=1, l=1, m=1, n=1, o=4, p=1, q=1, r=2, s=1, t=2, u=2, v=1, w=1, x=1, y=1, z=1}
Total letter count is 35



回答6:


You can solve it with Regex If Regex wont be considered as High-tech 🙂

Idea is simple: Remove all letters and subtract output from original string length to get counter

String sentence = "Once upon a time...";
String noLetterString = sentence.replaceAll("[a-zA-Z]", "");
int counterLetter = sentence.length() - noLetterString.length();
System.out.println("counter:" + counterLetter);

By old school programming 🙂 Idea here is in reverse, appending only letters

String sentence = "Once upon a time...";
String lowerCase = sentence.toLowerCase(); // to avoid comparison to UpperCase letters
StringBuilder counterStr = new StringBuilder();
for (char l : lowerCase.toCharArray()) {
    if (l >= 'a' && l <= 'z') {
        counterStr.append(l);
    }
}

System.out.println("counterStr:" + counterStr);
System.out.println("counter:" + counterStr.length());



回答7:


Here is the Update Code :

int[] array = new int[26] ;

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

    if(sentence.contains("."))
    {
        String sentenceNoSpace = sentence.replace(" ", "").toLowerCase() ;
        String sentenceFinal = sentenceNoSpace.substring(0, sentenceNoSpace.indexOf(".")) ;

        for (char c : sentenceFinal.toCharArray()) 
        {
            System.out.println(c+"  "+(c-97)); 
            array[c-97] += 1;     
        }

      // System.out.println("\n" + Arrays.toString(array)) ;

        for(int i=0; i< array.length;i++) {

            if(array[i] != 0) {

            char c = (char)(i+97);
            System.out.println(c+" occured "+ array[i]+" times");
          }
        }
    }
    else
    {
       System.out.println("You forgot a period. Try again.") ;
    }


来源:https://stackoverflow.com/questions/51605038/java-counting-letters-in-a-sentence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!