Count no.of digits in a String in Java

Counting number of numbers!


An example on counting no.of numbers in a string in Java.


Example


/* Licensed under GNU GPLV2. Taken from gowtham.gutha.util.StringOps */

// Import for Scanner class
import java.util.*;
class NumCount
{

public static void main(String args[])
{

// Create Scanner object for reading input from command prompt
Scanner s=new Scanner(System.in);

// Take input from the user and store it in st
String st=s.nextLine();

// Initialize variable count to 0
int count=0;

// Convert given string to char array
char[] c=st.toCharArray();

// Loop till end of string
for(int i=0;i<st.length();i++)
{
// Get ascii value of each char and store it in k
int k=(int)c[i];

// Digits ascii values start from 48 till 57
if((k>=48)&&(k<=57))
{
count++;
}
}

// Print the no.of digits
System.out.println("No.of digits are "+count);

// You can also print no.of chars other than digits like..
System.out.println("No.of chars other than digits are "+(st.length()-count));

}
}

The code is taken from gowtham.gutha.util.StringOps, it is licensed under GNU GPLV2, take time to use the framework if you don't wish to write the logic, also read terms and conditions of the license.

Also see Counting alphabets in string in Java


Posted by at on

Tags: String Handling,