user2843446
user2843446

Reputation: 59

Count letters in a string Java

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

Upvotes: 2

Views: 54344

Answers (5)

Hemanth Thati
Hemanth Thati

Reputation: 1

import java.io.*;

public class CharCount {

public static void main(String[] args) throws IOException
{
    int i,j=0,repeat=0;
    String output="",input;
    char c=' ';
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("enter name ");
    input=br.readLine();
    System.out.println("entered String ->\""+input+"\"");
    input=input.toLowerCase();

    for(i=0;i<input.length();i++)
    {
        for(j=0;j<output.length();j++)
        {
            if(input.charAt(i)==output.charAt(j) || input.charAt(i)==c)
            {
                repeat=1;
                break;
            }
        }
        if(repeat!=1)
        {
            output=output+input.charAt(i);
        }
        repeat=0;
    }

    System.out.println("non-reepeated chars in name ->\""+output+"\"");

    int count[]=new int[output.length()];
    for(i=0;i<output.length();i++)
    {
        for(j=0;j<input.length();j++)
        {
            if(output.charAt(i)==input.charAt(j))
                count[i]=count[i]+1;
        }
    }
    for(i=0;i<output.length();i++)
        System.out.println(output.charAt(i)+"- "+count[i]);
}

}

Upvotes: 0

Masudul
Masudul

Reputation: 21961

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.
      }         
 }

Upvotes: 15

Tobias Kremer
Tobias Kremer

Reputation: 1641

No you should not create an array of 26. This will break if the string contains unexpected characters. (ä, ö, ü anyone?) As I pointed out im my comment use a Map. This will work forr all posible characters out there.

Upvotes: 0

FazoM
FazoM

Reputation: 4956

You can create an Array which first element will represent 'a', second 'b', etc. If you need distinction between lower and upper cases than you can add it at the end. This array will have all values equals 0 at the beginning. Then you iterate through your sentence and you increment required values on the array. At the end you print all values that are > 0. Simple?

Let me know if you need more help

Upvotes: 0

Colin D
Colin D

Reputation: 5661

  • 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.

Upvotes: 2

Related Questions