w3resource

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:

Java: Count the letters, spaces, numbers and other characters of an input string

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:

Flowchart: Java exercises: Count the letters, spaces, numbers and other characters of an input string

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.



Share this Tutorial / Exercise on : Facebook and Twitter

Java: Tips of the Day

Prefer primitive classes

Wrapper classes are often slower than primitive classes. While Primitive class only has values, the wrapper class stores information about the entire class. Since the classes often deal with object values, comparing them with primitive classes does not give the desired results.

Ref: https://bit.ly/3eItLCN