check if string has special characters java
//1. Using Regex
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaHungry {
public static void main(String args[]) {
String inputString = "Alive*is*Awesome$";
Pattern pattern = Pattern.compile("[^a-zA-Z0-9]");
Matcher matcher = pattern.matcher(inputString);
boolean isStringContainsSpecialCharacter = matcher.find();
if(isStringContainsSpecialCharacter)
System.out.println(inputString+ " contains special character");
else
System.out.println(inputString+ " does NOT contain special character");
}
}
//Output:
//Alive*is*Awesome$ contains special character
//2. Without Using Regex
public class JavaHungry {
public static void main(String args[]) {
String inputString = "Alive*is*Awesome$";
String specialCharactersString = "!@#$%&*()'+,-./:;<=>?[]^_`{|}";
for (int i=0; i < inputString.length() ; i++)
{
char ch = inputString.charAt(i);
if(specialCharactersString.contains(Character.toString(ch))) {
System.out.println(inputString+ " contains special character");
break;
}
else if(i == inputString.length()-1)
System.out.println(inputString+ " does NOT contain special character");
}
}
}