How do I see if a substring exists inside another

2020-02-06 18:28发布

问题:

How can I tell if the substring "template" (for example) exists inside a String object?

It would be great if it was not a case-sensitive check.

回答1:

Use a regular expression and mark it as case insensitive:

if (myStr.matches("(?i).*template.*")) {
  // whatever
}

The (?i) turns on case insensitivity and the .* at each end of the search term match any surrounding characters (since String.matches works on the entire string).



回答2:

String.indexOf(String)

For a case insensitive search, to toUpperCase or toLowerCase on both the original string and the substring before the indexOf

String full = "my template string";
String sub = "Template";
boolean fullContainsSub = full.toUpperCase().indexOf(sub.toUpperCase()) != -1;


回答3:

You can use indexOf() and toLowerCase() to do case-insensitive tests for substrings.

String string = "testword";
boolean containsTemplate = (string.toLowerCase().indexOf("template") >= 0);


回答4:

String word = "cat";
String text = "The cat is on the table";
Boolean found;

found = text.contains(word);