Java Program to count digits and white spaces in a given string
Program
import java.util.Scanner;
public class CountDigitsAndWhiteSpacesInString {
public void countDigitWhiteSpaces(String inputStr)
{
int digitCount = 0;
int spacesCount = 0;
inputStr = inputStr.toLowerCase();
for(int i = 0; i < inputStr.length(); i++) {
//check for Digits
if(inputStr.charAt(i) >='0' && inputStr.charAt(i) <='9') {
// Increment digit count
digitCount++;
}
//Checks for White Spaces
else if(inputStr.charAt(i) == ' ') {
//Increment spaces count
spacesCount++;
}
}
System.out.println("Number of Digits: "+ digitCount);
System.out.println("Number of Whitespaces: "+ spacesCount);
}
public static void main(String[] args)
{
CountDigitsAndWhiteSpacesInString countDigitsAndWhiteSpacesInString = new CountDigitsAndWhiteSpacesInString();
Scanner reader = new Scanner(System.in);
System.out.print("Enter the String: ");
String inputString = reader.nextLine();
countDigitsAndWhiteSpacesInString.countDigitWhiteSpaces(inputString);
}
}
This program counts the number of digits and white spaces in a given string by iterating through each character and identifying its type.
-
Input:
- The program accepts a string from the user using the
Scanner
class.
- The program accepts a string from the user using the
-
Initialization:
- Two counters are initialized:
digitCount
andspacesCount
to track the number of digits and white spaces in the string.
- Two counters are initialized:
-
String Conversion:
- The input string is converted to lowercase using
toLowerCase()
for uniform processing (though not strictly necessary for digit and space counting).
- The input string is converted to lowercase using
-
Iteration Through Characters:
- A
for
loop iterates through each character in the string:- Digit Check:
- Each character is checked if it is between
'0'
and'9'
. - If it matches, the
digitCount
is incremented.
- Each character is checked if it is between
- White Space Check:
- The character is checked if it is equal to
' '
(a space character). - If it matches, the
spacesCount
is incremented.
- The character is checked if it is equal to
- Digit Check:
- A
-
Output:
- The program prints the counts of digits and white spaces.
Key Features:
- Character Classification:
- Differentiates between digits and spaces.
- Efficiency:
- Processes the string in a single loop.
- Simple Logic:
- Uses basic conditional checks for digits and spaces.
Output
$ javac CountDigitsAndWhiteSpacesInString.java
$ java CountDigitsAndWhiteSpacesInString
Enter the String: oodlescoop 123
Number of Digits: 3
Number of Whitespaces: 1