Problem Statement:
Write a Java program to count the letters, spaces, numbers and other character of an input String.
Steps to solve this program:
- Take inputs.
- Apply for loop for each and every character checking process inside method.
- Count letter inside the string.
- Count numbers inside the string
- Count spaces and other characters inside the string.
- Call method inside main method
- Display all the counting variables
- Take Inputs
Take all string inputs and initialize all the counting variable as 0.
char[] ch = x.toCharArray();
int letter = 0;
int space = 0;
int num = 0;
int otherchat = 0;
- Apply for loop for checking each and every character inside method:
Using for loop from 0 to string length for iteration process inside count method.
public static void count(String x) {
for (int i = 0; i < x.length(); i++) { ... }
}
- Count letter inside the string:
Using if and isLetter() to count the total letters present inside string.
if (Character.isLetter(ch[i])) {
letter++;
}
- Count digits inside the string:
Using if and isDigit() to count the total digits present inside String.
else if (Character.isDigit(ch[i])) {
num++;
}
- Count spaces and other characters inside the string:
Using if and isSpaceChar() and else part is used to count the total spaces and other characters present inside string.
else if (Character.isSpaceChar(ch[i])) {
space++;
} else {
otherchat++;
}
- Call count method inside main method:
Inside main method call count(test) for displaying every count variables.
public static void main(String[] args) {
String test = "@Atechdaily.com 123456";
count(test);
}
- Display all counting variables:
After storing all values inside counting variable now print all the values inside method.
System.out.println("letter: " + letter);
System.out.println("space: " + space);
System.out.println("number: " + num);
System.out.println("other: " + otherchat);
Full Java Code:
import java.util.Scanner;
public class Javaexcercise {
public static void main(String[] args) {
String test = "@Atechdaily.com 123456";
count(test);
}
public static void count(String x) {
char[] ch = x.toCharArray();
int letter = 0;
int space = 0;
int num = 0;
int otherchat = 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 {
otherchat++;
}
}
System.out.println("The string is :"+x);
System.out.println("letter: " + letter);
System.out.println("space: " + space);
System.out.println("number: " + num);
System.out.println("other: " + otherchat);
}
}
Console Output
The string is :@Atechdaily.com 123456
letter: 13
space: 1
number: 6
other: 2