Java Exercises: Count the letters, spaces, numbers and other characters of an input string
Java Basic: Exercise-38 with Solution
Write a Java program to count the letters, spaces, numbers and other characters of 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:
import java.util.Scanner;
public class Exercise38 {
public static void main(String[] args) {
String test = "Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33";
count(test);
}
public static void count(String x){
char[] ch = x.toCharArray();
int letter = 0;
int space = 0;
int num = 0;
int other = 0;
for(int i = 0; i < x.length(); i++){
if(Character.isLetter(ch[i])){
letter ++ ;
}
else if(Character.isDigit(ch[i])){
num ++ ;
}
else if(Character.isSpaceChar(ch[i])){
space ++ ;
}
else{
other ++;
}
}
System.out.println("The string is : Aa kiu, I swd skieo 236587. GH kiu: sieo?? 25.33");
System.out.println("letter: " + letter);
System.out.println("space: " + space);
System.out.println("number: " + num);
System.out.println("other: " + other);
}
}
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:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to reverse a string.
Next: Write a Java program to create and display unique three-digit number using 1, 2, 3, 4. Also count how many three-digit numbers are there.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework