简体   繁体   中英

check whether a string contains only letters spaces and quotes (preferably no regex)

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM