In this tutorial we will learn how to Count number of special characters in a string in Java with sum cool and easy examples.
In many situation, you might have to come up with this type of requirement .I know you are here just because you are in need of this awesome trick to Count number of special characters in a string in Java .
if you don’t know how to count all tha special characters then you are at the right place. Becoause in this tutorial we gonna count special characters as an user input in Java
Count number of special characters in a string in Java !
Let’s learn this with some easy examples,
At first create a string which can hold the value entered by the user.(user input)
import java.util.*; public class Specila_Chara { public static void main(String[] args) { Scanner sc=new Scanner (System.in); System.out.println(" enter any string"); String s=sc.nextLine(); int c=0; char ch; for(int i=0;i<s.length();i++) { ch=s.charAt(i); if (!(ch>='A'&&ch<='Z')||!(ch>='a'&&ch<='z') ||!(ch>=0&&ch<=9)||(ch==' ')) { c++; } } System.out.println( "special Characters = " + c); } }
Output :
Enter any string :
Input :
(R@J @GR@H@R! !& @ G@@D b@Y)$^$C!eNcE%
Output :
special Characters = 38
Summary :
Special characters are those characters that are neither a letter nor a number. Whitespace is also not considered a special character. Examples of special characters are:- !(exclamation mark), , (comma), #(hash), .
import java.util.Scanner;
The Java. util package contains the scanner in Java .Scanner is a class available in the java. util package. It is used to take input from a user for any primitive datatype (int, float, string, and so on).
for(int i=0;i<s.length();i++) { ch=s.charAt(i);
For input the srting in java.