Program to find special characters in a string
In this section, you will learn how to find special characters from a string in Java along with counting the total number of special characters with their positions in a given string.
Let's try to create a simple example :
➤ Example : FindSpecialChar.java;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
class FindSpecialCharactetrs {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
String str;
System.out.print("\nEnter a string : ");
str = input.nextLine();
Pattern string_patterns = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher string_matcher = string_patterns.matcher(str);
System.out.println("\n\n\t______________ OUTPUT ______________");
System.out.println("\nYour string is : "+str);
int count = 0;
while(string_matcher.find()) {
count = count + 1;
System.out.println("\tposition "+string_matcher.start() +": "+ str.charAt(string_matcher.start()));
}
System.out.println("\nThere are "+count+" special characters");
System.out.println("\n\t------------------------------------");
}
}
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.Scanner; class FindSpecialCharactetrs { public static void main(String args[]) { Scanner input = new Scanner(System.in); String str; System.out.print("\nEnter a string : "); str = input.nextLine(); Pattern string_patterns = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE); Matcher string_matcher = string_patterns.matcher(str); System.out.println("\n\n\t______________ OUTPUT ______________"); System.out.println("\nYour string is : "+str); int count = 0; while(string_matcher.find()) { count = count + 1; System.out.println("\tposition "+string_matcher.start() +": "+ str.charAt(string_matcher.start())); } System.out.println("\nThere are "+count+" special characters"); System.out.println("\n\t------------------------------------"); } }
Output 1:
Enter a string : `Welcome to #coderwebsite && "j@v@" is @m@zing programming l@ngu@ge`!
______________ OUTPUT ______________
Your string is : `Welcome to #coderwebsite && "j@v@" is @m@zing programming l@ngu@ge`!
position 0: `
position 12: #
position 26: &
position 27: &
position 29: "
position 31: @
position 33: @
position 34: "
position 39: @
position 41: @
position 60: @
position 64: @
position 67: `
position 68: !
There are 14 special characters
------------------------------------
Output 2:
Enter a string : Welcome to coderwebsite
______________ OUTPUT ______________
Your string is : Welcome to coderwebsite
There are 0 special characters
------------------------------------
Comments
With industry specific excellence in PHP development services, we will make your biz grow and enhance your user’s experience. Please check out our PHP Development Company
Awesome Blog thanks for share your valuable information
Inwizards Technology - Internet of Things IoT
iot development company
hire iot developer