Paul Labis: This is a personal blog where everyone can read my experiences, ideas and thoughts about programming, latest gadgets and other information technology related topics, lifestyle and many other stuff I would like to share to the public.

Check If a String Contains a Substring in Java

This article shows some useful ways on checking a string that contains a substring. I find this topic relevant to document as I may someday use this on another project. Also, other developers might look for an article online to help them solve their problem. Since this topic is very basic Java, I only added short description and sample code below. 

//Create a string to evaluate
String phrase = "The big brown fox jumped over the lazy dog!";

//Check if it contains a case sensitive substring
boolean evaluation = phrase.contains("brown"); //returns true
evaluation = phrase.contains("Brown"); //returns false
evaluation = phrase.indexOf("fox jumped") > 0; //returns true

//Check if phrase starts with a substring
evaluation = phrase.startsWith("Th"); //returns true

//Check if phrase ends with a substring
evaluation = phrase.endsWith("og"); //returns true

//To check string with ignore case, we should be using regular expression
evaluation = string.matches("(?i).*i am.*"); //returns true

//Check if phrase starts with a substring
evaluation = string.matches("(?i)th.*"); //returns true

//Check if phrase ends with a substring
evaluation = string.matches("(?i).*adam"); //returns true

That is all for this article. I hope this helps you.