![](/img/trans.png)
[英]How to check whether a String contains '\r' \t' '\n'…other than spaces
[英]java - check whether a string contains any characters other than spaces
我需要检查字符串是否包含空格以外的任何符号。 我不能与
String.length() > 0
要么
String.equals("")
因为空格被视为字符。 如何确定java字符串是否包含其他字符(字母,符号,数字等)?
只需trim()
字符串即可(记住在调用该方法之前要检查null
):
返回字符串的副本,省略前导和尾随空格。
myString != null && !myString.trim().isEmpty();
或者,如果您使用的是Apache Commons,则可以使用StringUtils.isBlank() 。 您可以检查其实现 。
您可以使用
String.trim().equals("")
如果String仅包含空格,则在检查是否相等之前,它们将全部由trim()
删除
为什么不使用String.trim()
并检查结果长度是否大于0?
使用正则表达式, "[^ ]"
。
String test;
//populate test
if(test.trim().length() > 0)
{
//Bingo
}else{
//Uff
}
删除所有空格:
String s = ...;
s = s.replaceAll("\\s+", "");
然后检查长度:
if(s.length() > 0)
或检查字符串是否为空:
if (s.isEmpty())
使用正则表达式:
myString.matches("[^ ]+"); // all but spaces
使用Google Guava:
CharMatcher.WHITESPACE.negate().matchesAnyOf(str)
修剪字符串,然后检查是否为空字符串。
您可以尝试执行以下操作,删除所有空格字符,然后测量其长度:
string.replaceAll("\\s","")
int length=string.length();
在这种情况下,如果length大于零,则它确实包含非空格字符。
希望这可以帮助 :)
您可以从Apache Commons使用StringUtils: http : //commons.apache.org/lang/api-3.1/index.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.