16. Checking that a string contains a substring

A very simple, one line of code solution relies on the String.contains() method.

This method returns a boolean value indicating whether the given substring is present in the string or not:

String text = "hello world!";
String subtext = "orl";

// pay attention that this will return true for subtext=""
boolean contains = text.contains(subtext);

Alternatively, a solution can be implemented by relying on String.indexOf() (or String.lastIndexOf()), as follows:

public static boolean contains(String text, String subtext) {

return text.indexOf(subtext) != -1; // or lastIndexOf()
}

Another solution can be implemented based on a regular expression, as follows:

public static boolean contains(String text, String subtext) {

return text.matches("(?i).*" + Pattern.quote(subtext) + ".*");
}

Notice that the regular expression is wrapped in the Pattern.quote() method. This is needed to escape special characters such as <([{^-=$!|]})?*+.> in the given substring.

For third-party library support, please consider Apache Commons Lang, StringUtils.containsIgnoreCase().
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset