如何查看子字符串是否存在于 Java 1.4 中的另一个字符串中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/687577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:57:00  来源:igfitidea点击:

How do I see if a substring exists inside another string in Java 1.4?

javastringsubstring

提问by joe

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

如何判断子字符串“模板”(例如)是否存在于 String 对象中?

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

如果它不是区分大小写的检查,那就太好了。

采纳答案by CoverosGene

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.matchesworks on the entire string).

(我)不区分大小写和转弯。*在搜索项的每一端匹配任何字符周围(因为String.matches适用于整个字符串)。

回答by John Ellinwood

String.indexOf(String)

String.indexOf(String)

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

对于不区分大小写的搜索,对原始字符串和 indexOf 之前的子字符串都使用 toUpperCase 或 toLowerCase

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

回答by Dan Lew

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

您可以使用 indexOf() 和 toLowerCase() 对子字符串进行不区分大小写的测试。

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

回答by Issac Balaji

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

found = text.contains(word);

回答by Raj

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