Java: Count the letters, spaces, numbers and other characters of an input string
Count Characters in String
Write a Java program to count letters, spaces, numbers and other characters in an input string.
Test Data:
The string is : Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33
Pictorial Presentation:
Sample Solution:
Java Code:
Explanation:
In the exercise above -
- The string to be analyzed is stored in the 'test' variable.
- The "count()" method takes a string 'x' as its parameter.
- Inside the "count()" method, the "toCharArray()" method is used to convert the input string x into an array of characters 'ch'.
- Four variables (letter, space, num, and other) are initialized to zero. These variables will be used to count the respective types of characters in the string.
- A for loop iterates through each character in the 'ch' array.
- Inside the loop, it checks the type of each character using various "Character" class methods like isLetter(), isDigit(), and isSpaceChar(). Depending on the type, it increments the corresponding counter variable (letter, num, space, or other).
- Finally, it prints the original string and the counts of each character type.
Sample Output:
The string is : Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33 letter: 23 space: 9 number: 10 other: 6
Flowchart:
For more Practice: Solve these Related Problems:
- Modify the program to count uppercase and lowercase letters separately.
- Write a program to find the most frequent character in a string.
- Ignore punctuation while counting letters.
- Implement character counting using a hash map.
Go to:
PREV : Reverse a String.
NEXT :
Unique Three-Digit Numbers.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.