有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何检查字符串是否包含搜索项

我有一个String和一个String[]填充了搜索项

如何检查我的String是否包含所有搜索项

以下是一个例子:

案例1:

String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "test";

案例2:

String text = "this is a stupid test";
String[] searchItems = new String[2];
searchItems[0] = "stupid";
searchItems[1] = "tes";

在案例1中,该方法应返回true,但在案例2中,该方法应返回false


共 (5) 个答案

  1. # 1 楼答案

    您可以在正则表达式中使用word boundaries来实现这一点:

    boolean result = true;
    for (String item : searchItems) {
        String pattern = ".*\\b" + item + "\\b.*";
        // by using the &&, result will be true only if text matches all patterns.
        result = result && text.matches(pattern);
    }
    

    这些边界确保搜索词只有在整个词出现在文本中时才会匹配。因此,"tes"将不会与"test"匹配,因为"\btes\b"不是"\btest\b"的子字符串

  2. # 2 楼答案

    我会尝试用空格分开绳子,然后把所有的夹板部分都圈起来

    为了让代码正常工作,可以这样做:

    String text = "this is a stupid test";
    List<String> searchItems = new ArrayList<String>();
    searchItems.add("stupid");
    searchItems.add("test");
    for(String word : test.split(" ")) {
       if(searchItems.contains(word)){
          //do your stuff when the condition is true ...
       } else {
          //do your stuff when the condition is false ...
       }
    }
    
  3. # 3 楼答案

    text.matches(".*\\b" + searchItems[0] + "\\b.*")
    

    注意:"\\b"将确保只匹配“整词”

  4. # 4 楼答案

    public boolean findIfAllItemsMatch(String[] searchItems, String text) {
        boolean allItemsMatch = true;
        for (String item_ : searchItems) {
            if(!text.contains(item_)) {  
                  allItemsMatch = false;
                  break;
             }
        }
        return allItemsMatch;
    }
    
  5. # 5 楼答案

    我会把课文中的所有单词排成一个数组。 然后用2个循环检查textArray是否包含所有搜索词

    public boolean search(String text, String[] searchItems) {
    
        String[] textArray = text.split(" ");
    
        for(String searchitem: searchItems) {
    
           boolean b = false;
    
           for(String word : textArray) {
    
               if(word.equals(searchitem)) {
                   b = true;
                   break;
               }
    
            }
    
         // text doesn't contain searchitem
         if(!b) return false;
    
         }
    
         return true;
    
    }