Java子串检查
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2314790/
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
Java substring check
提问by Arav
I have a String2. I want to check whether String2 exists in String1. String1's length can be less or greater or equal than String2. Also String2 can be null or empty sometimes. How can I check this in my Java code?
我有一个 String2。我想检查 String2 是否存在于 String1 中。String1 的长度可以小于或大于或等于 String2。String2 有时也可以为 null 或为空。如何在我的 Java 代码中检查这一点?
采纳答案by brabster
The obvious answer is String1.contains(String2);
显而易见的答案是 String1.contains(String2);
It will throw a NullPointerException if String1
is null. I would check that String1
is not null before trying the comparison; the other situations should handle as you would expect.
如果String1
为 null ,它将抛出 NullPointerException 。String1
在尝试比较之前,我会检查它是否为空;其他情况应该按照您的预期处理。
回答by perimosocordiae
You should try using String#contains.
您应该尝试使用String#contains。
回答by krassib
Here is a simple test class:
这是一个简单的测试类:
public class Test002 {
public static void main(String[] args) {
String string1 = "Java is Great!";
String string2 = "eat";
if (string1 != null && string2 != null & string2.length() <= string1.length() & string1.contains(string2)) {
System.out.println("string1 contains string2");
}
}
}
回答by lins314159
For older versions, you could use indexOf. If string2 is not in string1, indexOf will give you -1. You need to ensure beforehand that both Strings are not null though to avoid a NullPointerException.
对于旧版本,您可以使用indexOf。如果 string2 不在 string1 中,indexOf 会给你 -1。您需要事先确保两个字符串都不为空,以避免出现 NullPointerException。