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?
+9
A:
The obvious answer is String1.contains(String2);
It will throw a NullPointerException if String2 is null. I would check that String2 is not null before trying the comparison; the other situations should handle as you would expect.
Brabster
2010-02-22 22:33:25
assuming they are using Java 5+
newacct
2010-02-22 22:40:27
Indeed. I hope that, given the near six years since the release of Java 5, we can in general make that assumption.
Brabster
2010-02-22 23:49:03
Um, there are plenty of IT shops (mine included, unfortunately) that are still using Java 1.4.
Neal Swearer
2010-02-23 13:22:10
Thanks a lot for the info
Arav
2010-02-23 22:33:43
+5
A:
If this is homework, you should probably tag it as such.
You should try using String#contains.
perimosocordiae
2010-02-22 22:33:42
+1, for pointing the OP to the API rather than spoonfeeding the code. This way the OP is forced to read the API to find out the parameters. Who knows while they do this they may even find other usefull methods and save them from posting another question in the forum.
camickr
2010-02-22 22:49:04
+1
A:
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");
}
}
}
krassib
2010-02-22 22:43:43
+2
A:
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.
lins314159
2010-02-22 23:16:50