Hi I have to compute if a given string is substring of a bigger string. For example
String str = "Hallo my world";
String substr = "my"
The method "contains" should return true because str contains substr (false otherwise).
I was looking for something like "contains" at the String class but I didn't find it. I suppose that the only solution is to use pattern matching. If this is the case which would be the better (cheapest) way to do this?
Thanks!
This checks if s2 is a substring of s1.
There is a
contains()
method! It was introduced in Java 1.5. If you are using an earlier version, then it's easy to replace it with this:use indexOf it will return -1 if no match (contains was added in 1.5, maybe you are using older jdk?) see "contains(CharSequence s)" method in String class in JDK 1.4.2 for details
String.indexOf(substr) complexity is O(n2).. Luixv asked a cheaper solution.. But as far as , I know there is no better algorithm than current one.
Consider the following code: