Arav
Arav

Reputation: 5247

Java substring check

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?

Upvotes: 8

Views: 34198

Answers (4)

brabster
brabster

Reputation: 43560

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.

Upvotes: 45

perimosocordiae
perimosocordiae

Reputation: 17797

You should try using String#contains.

Upvotes: 7

lins314159
lins314159

Reputation: 2520

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.

Upvotes: 6

krassib
krassib

Reputation: 66

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

    }
}

Upvotes: 3

Related Questions