Home > Enterprise >  how to print count of each character in a string using java
how to print count of each character in a string using java

Time:12-16

Hey I am trying to figure out the logic in counting the each character in a string by comparing it to the first character in the string but I cannot seem to figure out the rest. If anyone can help complete this.

public class Main {
    public static void main(String[] args) {
        String word = "AaaaABBbccKLk";
        countLetter(word);
    }

    public static void countLetter(String word){
        int count = 0;
        char firstChar = word.toLowerCase().charAt(0);
        char ch;

        for(int i = 0 ; i<word.length(); i  ){
            ch = word.toLowerCase().charAt(i);

            if(ch == firstChar){
                System.out.println(ch   "="   count);
                count  ;
            }
            if(ch != firstChar && count > 0){
                count=0;
                System.out.println(ch   "="   count);
                count= count   1;
            }
        }
    }
}

CodePudding user response:

I assume you may want something like this:

class Main {

 public static void main(String[] args) {
    String word = "AaaaABBbccKLk";
    countLetter(word);
  }
  public static void countLetter(String word){
    int[] charCount = new int[26];
    word = word.toLowerCase();
    for(int i = 0; i < word.length(); i  ){
      char letter = word.charAt(i);
      int index = (int)letter - 97;
      charCount[index]  ;
    }
    for(int i = 0; i < charCount.length; i  ){
      System.out.println("Occurrences of "   (char)(i   97)   " :"   charCount[i]);
    }
  }
}

Though this code only works for Strings with characters A-Z, you can easily make this work for a larger range of characters by expanding the size of charCount and using an ASCII table.

The way this code works is that it creates an integer array of size 26 (the number of English letters) and then lowercases the String because in programming, lowercase and uppercase letters are actually different.

Next, we iterate through the word and convert every letter into an index by converting it to its ASCII value and subtracting 97 so that we get characters in the range 0 to 25. This means that we can assign each letter to an index in our array, charCount.

From here, we just increment the element of our array that corresponds to the index of each letter.

Finally, we just print out every letter and its frequency.

Let me know if you have any questions! (Also in the future, try to give a bit more insight into your process so it is easier to guide you instead of just giving the answer).

  • Related