有 Java 编程相关的问题?

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

如果字符串中的“xyz”前面没有句点,java返回true?

我试图解决这个编码问题:

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.

xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → true

我的尝试:

public boolean xyzThere(String str) {
  boolean res = false;

  if(str.contains(".xyz") == false && str.contains("xyz")){
    res = true;
  }

  return res;

}

问题是,is通过了除以下测试之外的所有测试,因为它包含两个xyz实例:

xyzThere("abc.xyzxyz")

我怎样才能让它通过所有测试


共 (6) 个答案

  1. # 1 楼答案

    或者,您可以将字符串中出现的所有“.xyz”替换为“”,然后使用。方法来验证修改后的字符串是否仍包含“xyz”。就像这样:

    return str.replace(".xyz", "").contains("xyz");
    
  2. # 2 楼答案

    public boolean xyzThere(String str) {
    return str.startsWith("xyz") || str.matches(".*[^.]xyz.*");
    }
    
  3. # 3 楼答案

    好吧,我知道每个人都渴望分享他们的专业知识,但直接给孩子答案没有什么好处

    @x94

    我通过了所有的测试,有三个陈述。这里有一个提示:尝试使用stringreplace方法。以下是方法签名:

    String replace(CharSequence target, CharSequence replacement)
    

    请注意,if语句中的第一个条件可以简化为:

    str.contains(".xyz") == false
    

    致:

    !str.contains(".xyz")
    

    contains方法已经返回true或false,因此不需要显式的equals比较

  4. # 4 楼答案

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

    编辑:鉴于“.xyzxyz”应返回true,解决方案应为:

    public boolean xyzThere(String str) {
        int index = str.indexOf(".xyz");
        if(index >= 0) {
            return xyzThere(str.substring(0, index)) || xyzThere(str.substring(index + 4));
        } else return (str.contains("xyz"));
    }
    
  5. # 5 楼答案

    您可以将等效的java代码用于以下解决方案:

    def xyz_there(str):
      pres = str.count('xyz')
      abs = str.count('.xyz')
      if pres>abs:
        return True
      else:
        return False
    
  6. # 6 楼答案

    public static boolean xyzThere(String str) {
        int i = -1;
        while ((i = str.indexOf("xyz", i + 1 )) != -1) {
            if (i == 0 || (str.charAt(i-1) != '.')) {
                return true;
            }
        }
        return false;
    }