write a java program to count special characters in a string.

In this Java program count Special Characters in a String.we first used for loop to iterate spl_str.
Inside the loop, to keep the code simple, we assigned (spl_str.charAt(i)) each character to ch parameter and pass to isSpecialChar method.
Within the first if condition (ch >= ‘a’ && ch <= ‘z’ || ch >= ‘A’ && ch <= ‘Z’ ), we check whether the character is an alphabet. If it is true, we set status false.
In the else if statement, we used (ch >= ‘0’ && ch <= ‘9’) to check whether the character is a digit, and if true, we set status false.else, we set status true and return true to isSpecialChar method in main and count how many time true status came.

				
					public class CountSpecialChar {
	public static void main(String[] args) {
		String spl_str = "?@abc*%@tyu!@asf123ASD";
		int count = 0;
		for (int i = 0; i < spl_str.length(); i++) {
			if (isSpecialChar(spl_str.charAt(i))) {
				count++;
			}
		}
		System.out.println("Total number of special character:- " + count);
	}

	public static boolean isSpecialChar(char ch) {
		boolean status = false;
		if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
			status = false;
		} else if (ch >= '0' && ch <= '9') {
			status = false;
		} else {
			status = true;
		}
		return status;
	}
}

				
			

Output :-
Total number of special character:- 7

Leave a Comment

Your email address will not be published. Required fields are marked *