Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Java program to count occurence of letters

  • 07-02-2010 05: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, Registered Users 2 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, Registered Users 2 Posts: 27,517 ✭✭✭✭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, Registered Users 2 Posts: 4,277 ✭✭✭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, Registered Users 2 Posts: 27,517 ✭✭✭✭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, Registered Users 2 Posts: 4,277 ✭✭✭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, Registered Users 2 Posts: 1,919 ✭✭✭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