如何检查一个字符串是否包含给定字符串,而不是另一个给定字符串的一部分?

时间:2018-08-07 10:30:21

标签: java string

例如,我有以下字符串:hello world, you're full of weird things

我想知道此字符串是否包含一个ll ,它不是字符串hell 的一部分,又在此示例中应返回true,因为存在ll一词中的full

如果字符串仅为hello world,则不会匹配,因为ll中的hello是给定hell字符串的一部分

4 个答案:

答案 0 :(得分:1)

public static boolean checkOccurance(String str,String findStr,,String butNotIn ){
        int lastIndex = 0;
        int count = 0;
        str = str.replace(butNotIn,"");
        while(lastIndex != -1){

            lastIndex = str.indexOf(findStr,lastIndex);

            if(lastIndex != -1){
                count ++;
                lastIndex += findStr.length();
            }
        }
        if(count>1){
          return true;
        }else{
          return false;
        }

调用方法

System.out.println( checkOccurance("hello world, you're full of weird things","ll","hell"));

输出

false

答案 1 :(得分:1)

您可以使用 RegExp Negative Lookbehind

public static boolean matches(String str) {
    final Pattern pattern = Pattern.compile("(?<!he)ll");
    Matcher matcher = pattern.matcher(str);
    return matcher.find();
}

测试:

    System.out.println(matches("hello world, you're full of weird things"));    // true
    System.out.println(matches("hello world")); // false

regex101.com

答案 2 :(得分:1)

您可以尝试以下方法吗:

String mainString = "hello world, you're full of weird things";
String findString = "ll";
String removeString = "hell";

String newString = mainString.Remove(mainString.IndexOf(removeString), removeString.Length);

if (newString.Contains(findString))
{
    return true;
}

答案 3 :(得分:0)

为什么不尝试查找butNotIn的边界(开始和结束索引),然后使用String#indexOf直到索引超出边界?

boolean isIn(String string, String word, String butNotIn) {
  int start = string.indexOf(butNotIn);
  int end = start+butNotIn.length;

  int position;
  do {
    position = string.indexOf(word);
  } while (position<start || position>end);
  return position>-1;
}