Accept String using Scanner and count its special character in Java
In this post, we will look at how to accept String using scanner and count the number of special characters in it.
Logic:
Let’s see how to do it.
We classify a character as a special char when,
- It is not an alphabet, this includes both upper and lower case
- It is not a digit
Program to count Special Character
import java.util.Scanner;
// Java code to demonstrate
// how to count special
// characters in a string using scanner
public class SpecialCharacterCounter {
public static void main(String[] args) {
// create the scanner
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the string with special character = ");
// scan the input string
String input = scanner.nextLine();
int counter = 0;
for (int i = 0; i < input.length(); i++) {
// check if the given character
// is a special character
if (isSpecialChar(input.charAt(i))) {
counter++;
}
}
System.out.println("Count of special character = " + counter);
// close the scanner
scanner.close();
}
// returns true if the input
// is a special character
public static boolean isSpecialChar(char ch) {
boolean isSpecialChar;
// check if ch is alphabet
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
isSpecialChar = false;
} else if (ch >= '0' && ch <= '9') {
isSpecialChar = false;
} else {
// passed character is a
// special character
// as it is neither alphabet
// nor digit
isSpecialChar = true;
}
return isSpecialChar;
}
}
Output:
Enter the string with special character = This%is@a$String*With&Special^Character Count of special character = 6