In this tutorial, we’ll explore a Java program for counting digits, letters, whitespace, and special characters in a string. This common interview question tests your Java expertise, particularly in string manipulation. Let’s dive in to strengthen your skills. This guide aims to provide practical insights into tackling such challenges, reinforcing essential Java concepts. Whether preparing for interviews or enhancing Java skills, you’ll gain the knowledge needed to efficiently analyze strings.
Java Program:
package TestAutomationCentral;
public class CountString {
public static void main(String[] args) {
// TestAutomationCentral.com
// Java Program to Count Digits, Letters, Whitespace and Special Characters in a String
String str = "!! Test Automation Central !! @ 12345";
int digits = 0, letters = 0, whitespaces = 0, special = 0;
for (char ch : str.toCharArray()) {
if (Character.isLetter(ch)) {
letters++;
} else if (Character.isWhitespace(ch)) {
whitespaces++;
} else if (Character.isDigit(ch)) {
digits++;
} else {
special++;
}
}
System.out.println("No. of Digits: " + digits);
System.out.println("No. of Letters: " + letters);
System.out.println("No. of Whitespaces: " + whitespaces);
System.out.println("No. of Special Character: " + special);
}
}
Output:
No. of Digits: 5
No. of Letters: 21
No. of Whitespaces: 6
No. of Special Character: 5