14

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.

Braiam
  • 1
  • 11
  • 47
  • 78
joe
  • 16,988
  • 36
  • 94
  • 131

5 Answers5

32

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
  • 14,291
  • 7
  • 38
  • 48
15

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

OtherDevOpsGene
  • 7,302
  • 2
  • 31
  • 46
  • 2
    I love regexes but its a bit overkill in that case – siukurnin Mar 27 '09 at 07:53
  • @CoverosGene when i added this code to search one column in my jtable then this code works perfect but has one issue that instead of searching the top most elements of String bit searches the down most elements first? Can you tell me what the wrong i am doing ??? – Syed Muhammad Mubashir Nov 03 '12 at 07:19
3
String word = "cat";
String text = "The cat is on the table";
Boolean found;

found = text.contains(word);
josliber
  • 43,891
  • 12
  • 98
  • 133
Issac Balaji
  • 1,441
  • 1
  • 13
  • 25
3

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

String string = "testword";
boolean containsTemplate = (string.toLowerCase().indexOf("template") >= 0);
Dan Lew
  • 85,990
  • 32
  • 182
  • 176
0
public static boolean checkIfPasswordMatchUName(final String userName, final String passWd) {

    if (userName.isEmpty() || passWd.isEmpty() || passWd.length() > userName.length()) {
        return false;
    }
    int checkLength = 3;
    for (int outer = 0; (outer + checkLength) < passWd.length()+1; outer++) {
        String subPasswd = passWd.substring(outer, outer+checkLength);
        if(userName.contains(subPasswd)) {
            return true;
        }
        if(outer > (passWd.length()-checkLength))
            break;
    }
    return false;
}
Scratte
  • 3,056
  • 6
  • 19
  • 26
Raj
  • 1
  • this will check if minimum 3 characters of substring (paswd) is contains in another string (Username) – Raj Apr 19 '20 at 05:42