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.

5 Answers 5

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;
Sign up to request clarification or add additional context in comments.

2 Comments

+1 and I'm deleting my answer. Yours is better for both parts of the question.
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
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).

2 Comments

I love regexes but its a bit overkill in that case
@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 ???
3

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

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

Comments

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

found = text.contains(word);

Comments

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;
}

1 Comment

this will check if minimum 3 characters of substring (paswd) is contains in another string (Username)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.