Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java program to count occurence of letters

Options
  • 07-02-2010 5:22pm
    #1
    Closed Accounts Posts: 425 ✭✭


    Hi this is my first time posting in this forum so forgive any mistakes! Okay so I'm learning Java in college and I need help with a program. The idea for the program is for the user to input a sentence, and the program will count how many times each letter is in the string, ie. "Abba" will give the results:
    A=2
    B=2

    I've made the input string into an array and my method is to search the array for letters. Here is the code so far:



    public class SentenceProgram {
    public static void main (String args[]) {

    Terminal terminal;
    String Sentence;
    char [] characterArray;

    terminal = new Terminal("Sentence Program");
    String stringSentence = terminal.readString("Enter in sentence: ");
    terminal.println("");


    char[] chars = stringSentence.toCharArray();

    /*count how many times 'A' is in the sentence*/
    int countA = 0;
    for(int i = 0; i < chars.length; i++) {
    if(chars == 'A')
    countA++;
    if (chars == 'a')
    countA++;
    }
    if (countA != 0)
    terminal.println ("Letter 'A' occurs: " + countA + " times");


    }
    }



    My problem is I'm not sure how to make a method to check every letter. In my code I have a method to check for upper and lower case a but I don't want to have to write this 26 times for every letter. Does anyone know how to write a method to search the array for every letter? Thanks.


Comments

  • Closed Accounts Posts: 404 ✭✭kenbrady


    string = string.trim();
    removes trailing leading white spaces, improves performance.

    string = string.toLowerCase();
    Now you don't have to check A and a

    Have an array of the alphabet and loop through it to test.
    letters[]

    Have an array of ints to represent the occurances. Set all to 0 first.
    occur[]


    Then the statement to print the results is
    String space = " = ";
    for(int i=0;i<26;i++){
    terminal.println(letters+space+occur);
    }


  • Closed Accounts Posts: 425 ✭✭TheRiddler


    Great got it working thanks! Mods you can close this now


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    Nah we'll leave it open as somebody else may have input or a question. I'll change it to [Solved] though.


  • Registered Users Posts: 27,088 ✭✭✭✭GreeBo


    You could also do something like

    Stringp[] alphas = new String {"a","b",...."z"};
    myString = "abcdshkjbdsd";

    len = myString.length();

    for (string char : alphas)
    myString = myString.replace(char, "");
    newLen = myString.length();
    print("num "+char+": "+len - newLen);
    len = newLen;
    done

    One benefit is that the string you are checking gets shorter and shorter each time.


  • Registered Users Posts: 4,275 ✭✭✭km991148


    Or sort it alphabetically (after doing tolower on it) then work through it as follows:

    for curr=0; curr<totallength; curr++{
    {
    while(curr!= curr+1)
    {count it}
    display letter and count
    update curr
    }


    Sorry I was bored - one of these ones with a hundred ways of implementing..
    Not even sure if there is any benefit to the above due to the sort..


  • Advertisement
  • Registered Users Posts: 27,088 ✭✭✭✭GreeBo


    km991148 wrote: »
    Sorry I was bored - one of these ones with a hundred ways of implementing..
    Not even sure if there is any benefit to the above due to the sort..

    Is there a better reason to be on here? :D

    I think the sort would kill you there though...


  • Registered Users Posts: 4,275 ✭✭✭km991148


    GreeBo wrote: »
    Is there a better reason to be on here? :D

    I think the sort would kill you there though...

    ha,

    ye to both..

    But then Sorting is a whole other exercise for the OP..


  • Registered Users Posts: 1,916 ✭✭✭ronivek


    An ideal procrastination opportunity.
    public static void printAlphabetCharOccurrences(String str)
    {
        int modifier = 97;
        int[] charCount = new int[('z' - 'a') + 1];
        String lowerCaseStr = str.toLowerCase();
        char c;
        for (int i = 0; i < lowerCaseStr.length(); i++) {
            if (Character.isLetter(c = lowerCaseStr.charAt(i))) {
                charCount[c - modifier]++;
            }
        }
    
        System.out.println("Occurrences of each letter in string: " + str);
        for (int i = 0; i < charCount.length; i++)
            System.out.println((char)(i + modifier) + ": " + charCount[i]);
    }
    


Advertisement