[英]How do I check that a Java String is not all whitespaces?
我想使用 Java 檢查 Java 字符串或字符數組是否不只是由空格組成?
這是一個非常相似的問題,除了它是 Javascript:
如何檢查字符串是否包含字符和空格,而不僅僅是空格?
編輯:我刪除了有關字母數字字符的部分,因此更有意義。
我能想到的最短解決方案:
if (string.trim().length() > 0) ...
這僅檢查(非)空白。 如果要檢查特定字符類,則需要使用強大的match()
和正則表達式,例如:
if (string.matches(".*\\w.*")) ...
...檢查至少一個(ASCII)字母數字字符。
我會使用 Apache Commons Lang 庫。 它有一個名為 StringUtils 的類,可用於各種字符串操作。 要檢查字符串是否全部為空格,您可以使用以下命令:
StringUtils.isBlank(<your string>)
這是參考: StringUtils.isBlank
比 Carl Smotricz 提到的略短:
!string.trim().isEmpty();
如果您使用的是Java 11或更新版本,新的isBlank
字符串方法isBlank
上用場:
!s.isBlank();
如果您使用的是Java 8、9 或 10 ,您可以構建一個簡單的流來檢查字符串是否僅是空格:
!s.chars().allMatch(Character::isWhitespace));
除了不需要任何第三方庫(例如 Apache Commons Lang)之外,這些解決方案還具有處理任何空白字符的優勢,而不僅僅是像許多其他答案中建議的基於trim
的解決方案那樣的純' '
空格。 您可以參考Javadocs以獲取所有支持的空白類型的詳盡列表。 請注意,這兩種情況也包括空字符串。
if(target.matches("\\S"))
// then string contains at least one non-whitespace character
注意使用反斜杠 cap-S,意思是“非空白字符”
我敢打賭這是最簡單的(也許是最快的?)解決方案。
這個答案更側重於旁注“即至少有一個字母數字字符”。 除此之外,它不會給其他(早期的)解決方案添加太多內容,只是在 String 為null
情況下它不會對 NPE 造成傷害。
如果 (1) s 為null
或 (2) s 為空或 (3) s 僅包含 whitechars,我們想要false
。
public static boolean containsNonWhitespaceChar(String s) {
return !((s == null) || "".equals(s.trim()));
}
如果您只檢查空格而不關心空值,那么您可以使用 org.apache.commons.lang.StringUtils.isWhitespace(String str),
StringUtils.isWhitespace(String str);
(檢查字符串是否僅包含空格。)
如果您還想檢查空值(包括空格),那么
StringUtils.isBlank(String str);
使用 Java-11+,您可以使用String.isBlank
API 來檢查給定的字符串是否全部由空格組成 -
String str1 = " ";
System.out.println(str1.isBlank()); // made up of all whitespaces, prints true
String str2 = " a";
System.out.println(str2.isBlank()); // prints false
同樣的javadoc是:
/**
* Returns {@code true} if the string is empty or contains only
* {@link Character#isWhitespace(int) white space} codepoints,
* otherwise {@code false}.
*
* @return {@code true} if the string is empty or contains only
* {@link Character#isWhitespace(int) white space} codepoints,
* otherwise {@code false}
*
* @since 11
*/
public boolean isBlank()
只是在 openjdk 13、Windows 10 上的性能比較。對於這些文本中的每一個:
"abcd"
" "
" \r\n\t"
" ab "
" \n\n\r\t \n\r\t\t\t \r\n\r\n\r\t \t\t\t\r\n\n"
"lorem ipsum dolor sit amet consectetur adipisici elit"
"1234657891234567891324569871234567891326987132654798"
執行以下測試之一:
// trim + empty
input.trim().isEmpty()
// simple match
input.matches("\\S")
// match with precompiled pattern
final Pattern PATTERN = Pattern.compile("\\S");
PATTERN.matcher(input).matches()
// java 11's isBlank
input.isBlank()
每 10.000.000 次。
結果:
METHOD min max note
trim: 18 313 much slower if text not trimmed
match: 1799 2010
pattern: 571 662
isBlank: 60 338 faster the earlier hits the first non-whitespace character
令人驚訝的是,trim+empty 是最快的。 即使它需要構造修剪后的文本。 仍然比簡單的 for 循環更快地尋找一個單一的非空白字符......
編輯:文本越長,不同的數字就越多。 修剪長文本比簡單的循環需要更長的時間。 但是,正則表達式仍然是最慢的解決方案。
修剪方法應該對你很有用。
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#trim()
返回字符串的副本,省略前導和尾隨空格。 如果此 String 對象表示一個空字符序列,或者此 String 對象表示的字符序列的第一個和最后一個字符的代碼都大於 '\ '(空格字符),則返回對此 String 對象的引用。
否則,如果字符串中沒有代碼大於 '\ ' 的字符,則創建並返回一個表示空字符串的新 String 對象。
否則,令 k 為代碼大於 '\ ' 的字符串中第一個字符的索引,並令 m 為代碼大於 '\ ' 的字符串中最后一個字符的索引。 創建一個新的 String 對象,表示這個字符串的子串,以索引 k 處的字符開始,以索引 m 處的字符結束——即 this.substring(k, m+1) 的結果。
此方法可用於從字符串的開頭和結尾修剪空格; 事實上,它還修剪了所有 ASCII 控制字符。
返回: 此字符串的副本,其中刪除了前導和尾隨空格,或者此字符串,如果它沒有前導或尾隨空格。前導或尾隨空格。
您可以修剪然后與空字符串進行比較,或者可能檢查長度是否為 0。
選擇:
boolean isWhiteSpaces( String s ) {
return s != null && s.matches("\\s+");
}
trim() 和其他提到的正則表達式不適用於所有類型的空格
即:Unicode 字符“行分隔符” http://www.fileformat.info/info/unicode/char/2028/index.htm
Java 函數 Character.isWhitespace() 涵蓋所有情況。
這就是為什么應該使用已經提到的解決方案StringUtils.isWhitespace( String ) / 或 StringUtils.isBlank(String) 的原因。
StringUtils.isEmptyOrWhitespaceOnly(<your string>)
將檢查: - 是否為空 - 是否只有空格 - 是否為空字符串“”
雖然我個人更喜歡!str.isBlank()
,正如其他人已經建議的那樣(或str -> !str.isBlank()
作為謂詞),這是上述str.trim()
方法的更現代和高效的版本,將使用str.strip()
- 將空值視為“空白”:
if (str != null && str.strip().length() > 0) {...}
例如作為謂詞,用於流,例如在單元測試中:
@Test
public void anyNonEmptyStrippedTest() {
String[] strings = null;
Predicate<String> isNonEmptyStripped = str -> str != null && str.strip().length() > 0;
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).noneMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r" };
assertTrue(Optional.ofNullable(strings).map(arr -> Stream.of(arr).anyMatch(isNonEmptyStripped)).orElse(true));
strings = new String[] { null, "", " ", "\\n", "\\t", "\\r", "test" };
}
public static boolean isStringBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.