how to count special character in a string?

In this program, we are going to learn how to count special character in a string. special characters are those characters that are neither a letter nor a number.

Approach :-

  • Declare a String variable as String str;
  • A for loop is used to count every total of the given string.
  • It is initialized as i=0, checks the condition whether i<str.length(); and executes the loop until the given condition becomes true.
  • Use an if condition to test if((ch >= ‘a’ && ch <= ‘z’) || (ch >= ‘A’ && ch <= ‘Z’) || (Character.getNumericValue(ch) >= 0 && Character.getNumericValue(ch) <= 9)), then status will be false.
  • Method Character.getNumericValue() returns the int value that the specified Unicode character represents.
  • If status will be true then we will maintain a counter for special character count.
  • Lastly, print the required count of special characters as per the need.
				
					public class CountSpecialChar {
	public static boolean isSpecial(char ch) {
		boolean status = true;

		if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
				|| (Character.getNumericValue(ch) >= 0 && Character.getNumericValue(ch) <= 9)) {
			status = false;
		} else {
			status = true;
		}

		return status;
	}

	public static void main(String[] args) {
		String str = "@$asd&*AM-jkg12vw";
		int count = 0;
		for (int i = 0; i < str.length(); i++) {
			if (isSpecial(str.charAt(i))) {
				count++;
			}
		}
		System.out.println("Total special character :-- " + count);
	}
}
				
			

Output :-
Total special character :– 5