8

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?

4 Answers 4

45

The obvious answer is 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.

Sign up to request clarification or add additional context in comments.

4 Comments

assuming they are using Java 5+
Indeed. I hope that, given the near six years since the release of Java 5, we can in general make that assumption.
Um, there are plenty of IT shops (mine included, unfortunately) that are still using Java 1.4.
If a NullPointerException cannot be tolerated, the check can be extended to String1 != null && String2 != null && String.contains(String2).
7

You should try using String#contains.

1 Comment

+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.
6

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.

Comments

3

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");
        }

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.