views:

2596

answers:

3

How can I tell if the substring "template" exists inside a String in java 1.4

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

Thanks!

+14  A: 

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;
John Ellinwood
+1 and I'm deleting my answer. Yours is better for both parts of the question.
Michael Myers
Of course if you plan to do a lot of comparisons don't forget to store an upper cased version of he most used string
siukurnin
+1  A: 

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

String string = "testword";
boolean containsTemplate = (string.toLowerCase().indexOf("template") >= 0);
Daniel Lew
+1  A: 

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).

CoverosGene
I love regexes but its a bit overkill in that case
siukurnin