how to count the number of alphabets in a given string in Java

In this tutorial, we will learn how to count the number of alphabets in a given string in Java.
As we all know String is a combination of alphabets, numerals, alpha-numerics, special characters like( “,” “@” “#” “?” “/” “+” “=” etc.,)
A string in Java is a user-defined combination whereas a character is a single character and it is declared in single quotes (‘ ‘) on the other hand strings are declared between double quotes (” “).
Now let us understand in detail on how to count the number of alphabets in a given string in Java.
Let us consider a simple example:
String str1=”coding is easier with code speedy @Code#####7786”
In the above example, there are six words with six alphabets in the word “coding”, two words in “is”, six words in “easier”, four words in “with”, four words in “code”, six words in “speedy” and also four words in “Code”.
coding-6 words
is-2 words
easier-6 words
with-4 words
code-4 words
speedy-6 words
Code-4 words
The output we need to obtain is 32 alphabets in the above string.
Let us understand it through a simple Java program.

Java program to count the number of alphabets in a given String

public class alphabetCount
{
  public static void main(String[] args) {
    String str1="coding is easier with code speedy @Code#####7786";
    int count=0;
    for (int i=0;i<str1.length();i++)
    {
       if(Character.isLetter(str1.charAt(i)))
count++;
    }
System.out.println("the number of alphabets in the given string is:"+count);
  }
}
 
        
output:
the number of alphabets in the given string is:32

 

In the above, we have used “for loop” a for loop is used for iteration i.e., user can iterate until the desired output is obtained.
And we have used “if”statement to check whether the given condition is true or false if the condition is true statements in the if conditions are executed and if the conditions are false the conditions are not executed.
In the above code, we have used Character.isLetter(str1.charAt()) condition to count the occurrence of each alphabet in the given string.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *