Ken*_*rey 49
为什么要使用正则表达式?
name.contains(" ")
Run Code Online (Sandbox Code Playgroud)
这应该也可以,并且更快.
一个简单的答案,与之前的答案类似:
str.matches(".*\\s.*")
Run Code Online (Sandbox Code Playgroud)
当您将所有这些放在一起时,如果字符串中的任何位置有一个或多个空格字符,则返回 true。
这是一个简单的测试,您可以运行它来对您的解决方案进行基准测试:
boolean containsWhitespace(String str){
return str.matches(".*\\s.*");
}
String[] testStrings = {"test", " test", "te st", "test ", "te st",
" t e s t ", " ", "", "\ttest"};
for (String eachString : testStrings) {
System.out.println( "Does \"" + eachString + "\" contain whitespace? " +
containsWhitespace(eachString));
}
Run Code Online (Sandbox Code Playgroud)
如果要使用Regex,则它已经为任何非空白字符提供了预定义的字符类“ \ S”。
!str.matches("\\S+")
Run Code Online (Sandbox Code Playgroud)
告诉您这是否是至少一个字符的字符串,其中所有字符均为非空格