如何检查 Java 字符串是否全部为空格? [英] How do I check that a Java String is not all whitespaces?
问题描述
我想使用 Java 检查 Java 字符串或字符数组是否不只是由空格组成?
I want to check that Java String or character array is not just made up of whitespaces, using Java?
这是一个非常相似的问题,除了它是 Javascript:
如何检查字符串是否包含字符 &空格,而不仅仅是空格?
This is a very similar question except it's Javascript:
How can I check if string contains characters & whitespace, not just whitespace?
EDIT:我删除了有关字母数字字符的部分,因此更有意义.
EDIT: I removed the bit about alphanumeric characters, so it makes more sense.
推荐答案
我能想到的最短的解决方案:
Shortest solution I can think of:
if (string.trim().length() > 0) ...
这只检查(非)空白.如果你想检查特定的字符类,你需要使用强大的 match()
和一个正则表达式,例如:
This only checks for (non) white space. If you want to check for particular character classes, you need to use the mighty match()
with a regexp such as:
if (string.matches(".*\w.*")) ...
...检查至少一个 (ASCII) 字母数字字符.
...which checks for at least one (ASCII) alphanumeric character.
这篇关于如何检查 Java 字符串是否全部为空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!