Java 检查字符串是否不包含字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19437022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if String Does Not Contain Character
提问by user2455722
I need to see if a String does not contain nothing in Java. Here is my code:
我需要查看一个字符串是否在 Java 中不包含任何内容。这是我的代码:
public class Decipher {
public static void main(String[] args) {
System.out.println("Opening...");
System.out.println("Application Open");
String s = "yyyd";
if(s.contains("")){
System.out.println("s contains Y");
s = s.replace("y", "a");
System.out.println(s);
}
}
}
How can I get it to tell if s doesn't contain anything?
我怎样才能知道 s 是否不包含任何内容?
回答by redFIVE
If you are checking against a null value, then you can use
如果您正在检查空值,则可以使用
if (s != null) {
dosomething();
}
If you want to check against an empty, instantiated string, then use
如果要检查空的实例化字符串,请使用
if (s.equals("") {
doSomethingElse();
}
null
strings and empty strings are two very different things.
null
字符串和空字符串是两个非常不同的东西。
回答by Laura
if im correct, you want to check if a string is empty right? The simplest way is like this
如果我正确,您想检查字符串是否为空,对吗?最简单的方法是这样的
if (string == null)
如果(字符串==空)
or, if you want to check if a string is null or has whitespace only
或者,如果您想检查字符串是否为空或只有空格
if (string.trim() == null)
if (string.trim() == null)
回答by whyem
You could use CommonsValidator -> GenericValidator
您可以使用CommonsValidator -> GenericValidator
// returns true if 's' does not contain anything or is null
GenericValidator.isBlankOrNull(s)
And not depending on external libraries
并且不依赖于外部库
if (s == null || s.trim().length() == 0) {
// do your stuff
}