Thursday, September 29, 2011

Java: Contains() method for String class


Share at Facebook

If you need to check whether a string contains inside another string or not, you can do this using the indexOf() method from String class. I didn't find the contains function or something similar to that from String class which will take String as parameter for checking.

Below is the code that you can use like contains(String string);


String string = "My Test String...";
String contains = "Test";
if(string.indexOf(contains) >= 0){
System.out.println("["+contains+"] is inside ["+string+"]");
}


Basically indexOf function returns the position of the string from searching string. An index always starts from 0 as we know.




No comments: