How can I find whitespace in a String?

后端 未结 14 1042
感动是毒
感动是毒 2020-12-01 05:08

How can I check to see if a String contains a whitespace character, an empty space or \" \". If possible, please provide a Java example.

For example: String

14条回答
  •  暖寄归人
    2020-12-01 05:39

    Check whether a String contains at least one white space character:

    public static boolean containsWhiteSpace(final String testCode){
        if(testCode != null){
            for(int i = 0; i < testCode.length(); i++){
                if(Character.isWhitespace(testCode.charAt(i))){
                    return true;
                }
            }
        }
        return false;
    }
    

    Reference:

    • Character.isWhitespace(char)

    Using the Guava library, it's much simpler:

    return CharMatcher.WHITESPACE.matchesAnyOf(testCode);
    

    CharMatcher.WHITESPACE is also a lot more thorough when it comes to Unicode support.

提交回复
热议问题