【问题标题】:How do I see if a substring exists inside another string in Java 1.4?如何查看 Java 1.4 中的另一个字符串中是否存在子字符串?
【发布时间】:2010-10-15 19:30:51
【问题描述】:

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

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

【问题讨论】:

    标签: java string substring


    【解决方案1】:

    String.indexOf(String)

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

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

    【讨论】:

    • +1 我正在删除我的答案。您的问题对这两个部分都更好。
    • 当然,如果您打算进行大量比较,请不要忘记存储他最常用字符串的大写版本
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      使用正则表达式并将其标记为不区分大小写:

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

      (?i) 开启不区分大小写,并且搜索词两端的 .* 匹配任何周围的字符(因为 String.matches 作用于整个字符串)。

      【讨论】:

      • 我喜欢正则表达式,但在那种情况下它有点矫枉过正
      • @CoverosGene 当我添加此代码以搜索我的 jtable 中的一列时,此代码运行良好,但有一个问题,即不是搜索字符串位的最顶部元素而是首先搜索最下面的元素?你能告诉我我做错了什么吗???
      【解决方案4】:
      String word = "cat";
      String text = "The cat is on the table";
      Boolean found;
      
      found = text.contains(word);
      

      【讨论】:

        【解决方案5】:
        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;
        }
        

        【讨论】:

        • 这将检查是否至少 3 个字符的子字符串(paswd)包含在另一个字符串(用户名)中
        猜你喜欢
        • 2017-02-21
        • 1970-01-01
        • 2013-05-12
        • 1970-01-01
        • 2019-05-11
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        相关资源
        最近更新 更多