Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count letters in a string Java

Tags:

java

arrays

I'm doing an assignment where I'll have to code a program to read in a string from user and print out the letters in the string with number of occurrences. E.g. "Hello world" in which it should print out "h=1 e=1 l=3 o=2 ... etc.", but mine only write "hello world" and the amount of letters in total. I can't use the hashmap function, only arrays. Can someone give me a hint or two on how to proceed from the written code below to get my preferred function? I don't understand exactly how to save the written input in array.

Here's my code so far.

public class CountLetters {
    public static void main( String[] args ) {
        String input = JOptionPane.showInputDialog("Write a sentence." );
        int amount = 0;
        String output = "Amount of letters:\n";

        for ( int i = 0; i < input.length(); i++ ) {
            char letter = input.charAt(i);
            amount++;
            output = input;
        }
        output += "\n" + amount;
        JOptionPane.showMessageDialog( null, output,
                             "Letters", JOptionPane.PLAIN_MESSAGE ); 
    }
}
like image 540
user2843446 Avatar asked Feb 20 '26 09:02

user2843446


2 Answers

You don't need 26 switch cases. Just use simple code to count letter:

    String input = userInput.toLowerCase();// Make your input toLowerCase.
    int[] alphabetArray = new int[26];
    for ( int i = 0; i < input.length(); i++ ) {
         char ch=  input.charAt(i);
         int value = (int) ch;
         if (value >= 97 && value <= 122){
         alphabetArray[ch-'a']++;
        }
    }

After done count operation, than show your result as:

 for (int i = 0; i < alphabetArray.length; i++) {
      if(alphabetArray[i]>0){
        char ch = (char) (i+97);
        System.out.println(ch +"  : "+alphabetArray[i]);   //Show the result.
      }         
 }
like image 56
Masudul Avatar answered Feb 22 '26 22:02

Masudul


  • Create an integer array of length 26.
  • Iterate each character of the string, incrementing the value stored in the array associated with each character.
  • The index in the array for each character is calculated by x - 'a' for lower case characters and x - 'A' for upper case characters, where x is the particular character.
like image 30
Colin D Avatar answered Feb 22 '26 21:02

Colin D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!