string count char java code example

Example 1: Write a Java program to count the letters numbers and other characters of an input string.

public static String countLetter(String str){
    String abc=str;
    int a=0,b=0;
    while(str.length()>0){
        int i=0;
        String ch=str.substring(i,i+1);
        if(ch.matches(".*[a-zA-Z].*")){
            a++;
        }else if (ch.matches(".*[0-9].*")){
            b++;
        }
        str=str.substring(i+1);
    }
    return abc + " has "+a+" letters "+b+" digit 
          and "+(abc.length()-(a+b))+" other characters ";
      
      
OR+++++++++++++++++++++++++++++++++
      
      
  static void findSum(String str)
{
   int total= str.length();
   str = str.replaceAll("\\s", "");
   int num =0;
   int letter=0;
   int i=0;
   while(i<str.length()){
      char ch = str.charAt(i);
      // if current character is a digit
      if (Character.isDigit(ch))
         num ++;
         // if current character is an alphabet
      else {
         letter++;
      }
      i++;
   }
   System.out.println(letter + " letters -> "+num +
                      " numbers -> "+ (total-letter-num) + " other chars");
}

Example 2: counting the number of characters in a string java

public static void main(String[] args) {
		int wordCount = 0;
		String word = "hill";
		for (char letter = 'a'; letter <= 'z'; letter++) {
			for (int i = 0; i < word.length(); i++) {
				if (word.charAt(i) == letter) {
					wordCount++;
				}
			}
			if (wordCount > 0) {
				System.out.println(letter + "=" + wordCount);
				wordCount = 0;
			}
		}
	}