Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a given string is substring from another string in Java

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!

like image 558
Luixv Avatar asked Jan 26 '11 12:01

Luixv


2 Answers

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:

str.indexOf(substr) != -1
like image 79
Joachim Sauer Avatar answered Nov 10 '22 16:11

Joachim Sauer


 String str="hello world";
        System.out.println(str.contains("world"));//true
        System.out.println(str.contains("world1"));//false
  • Javadoc
like image 28
jmj Avatar answered Nov 10 '22 16:11

jmj