How to count the number of digits in a given string in Java

In this tutorial, we will learn how to count the number of digits in a given string in Java.
As we all know a string in Java is a user-defined of alphabets, numerals, alpha-numeric, special character etc.,
Whereas a ‘character’ is also a user-defined single character.
Characters are defined between single quotes(‘ ‘).
Similarly, Strings are defined between double quotes(” “).

Let us understand how to count the number of digits in a given string through a simple example:
String s=" coding is easier in Java 1234567890";


Here in the above example, there are ten digits and twenty alphabets.
“coding is easier in Java”-20 alphabets;
“1234567890”- 10 digits.
The output we need is to count the number of digits i.e. we need to get an output as 10 digits i.e, there are 10 numbers in the above string.

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

public class countDigits
{
	public static void main(String[] args) {
		String s="coding is easier in Java 1234567890";
		int count=0;
		for(int i=0;i<s.length();i++)
		{
			if(Character.isDigit(s.charAt(i)))
			count++;
		
		}
		System.out.println("the number of digits in the given string is:" + count);
	}
}
output:

the number of digits in the given string is:10

In the above Java program, we used ‘for loop’ for iteration until the desired output is obtained.
And ‘if’ statement to check the conditions are either true or false.
If the conditions are true ‘if’ block is executed.
Character.isDigit(s.charAt(i)) will count the number of digits in the given string.
‘Character.isDigit’ will count the number of each digit in the string. Similarly, we can also find the number of digits in any given string in Java using the above program.

Also read:

Leave a Reply

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