Reputation: 152
I am trying to check if a string has only letters (both uppercase and lowercase), spaces and quotes (both double and single) in it. I can't quite come up with an elegant way of doing this. The only thing I could come up with is making a list of the allowed characters and checking if each character of the string is in that list.
Upvotes: 4
Views: 5735
Reputation: 17454
If you do not want REGEX, you may check character by character in the String:
public static boolean onlyLetterSpaceQuotes(String str){
for(int x=0; x<str.length(); x++){
char ch = str.charAt(x);
if (!((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ch == ' '
|| ch == '\'' || ch == '\"'))
return false;
}
return true;
}
Test:
System.out.println(onlyLetterSpaceQuotes("abc \"A\'BC"));
System.out.println(onlyLetterSpaceQuotes("abc \"A\'BC123"));
Output:
true
false
Upvotes: 0
Reputation: 17454
You can do it like this:
str.matches("[a-zA-Z\\s\'\"]+");
You said preferably no REGEX, but you wanted an elegant way. In my opinion this would be an easy, short and elegant way to get what you want.
Upvotes: 2