Java Program to count letters in a String

Java 8Object Oriented ProgrammingProgramming

Let’s say we have the following string, that has some letters and numbers.

String str = "9as78";

Now loop through the length of this string and use the Character.isLetter() method. Within that, use the charAt() method to check for each character/ number in the string.

for (int i = 0; i < str.length(); i++) {
   if (Character.isLetter(str.charAt(i)))
   count++;
}

We have set a count variable above to get the length of the letters in the string.

Here’s the complete example.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "9as78";
      int count = 0;
      System.out.println("String: "+str);
      for (int i = 0; i < str.length(); i++) {
         if (Character.isLetter(str.charAt(i)))
         count++;
      }
      System.out.println("Letters: "+count);
   }
}

Output

String: 9as78
Letters: 2

Let us see another example.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "amit";
      int count = 0;
      System.out.println("String: "+str);
      for (int i = 0; i < str.length(); i++) {
         if (Character.isLetter(str.charAt(i)))
         count++;
      }
      System.out.println("Letters: "+count);
   }
}

Output

String: amit
Letters: 4
raja
Published on 13-Nov-2018 10:12:41
Advertisements