java .contains没有返回正确的布尔值?

问题描述 投票:-3回答:1

发生简单问题。不知道为什么它不起作用?附上截图。

screenshot

java contains
1个回答
0
投票

所以你需要这个:

public static boolean xyzThere(String s) {
  return !s.contains(".xyz") && s.contains("xyz");
}

并打破它。

对于初学者来说,仅仅指出字符串是否包含xyz是不够的,因为(如在失败的测试用例中)字符串中可能存在许多xyz实例。

所以你需要弄清楚逻辑是什么。

表达它的一种方式是说:

除非至少有一个序列xyz不是.xyz,否则我们总是会失败

所以也许我们正在寻找一个循环。

public static boolean xyzThere(String str) {
    boolean result = false;
    String s = str;
    int n = s.indexOf("xyz");
    while(n >= 0) {
        // if n is 0 then there was no preceeding dot so we win
        if (n == 0) { return true; }
        // if the immediately preceedding character was not a '.' return true
        char c = s.charAt(n-1);
        if (c != '.') { return true; }
        // otherwise keep looking until no more instances of "xyz" in the string
        s = s.substring(n + 3);
        n = s.indexOf("xyz");
    }
    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.