如果字符串中的“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")
我怎样才能让它通过所有测试
# 1 楼答案
或者,您可以将字符串中出现的所有“.xyz”替换为“”,然后使用。方法来验证修改后的字符串是否仍包含“xyz”。就像这样:
# 2 楼答案
# 3 楼答案
好吧,我知道每个人都渴望分享他们的专业知识,但直接给孩子答案没有什么好处
@x94
我通过了所有的测试,有三个陈述。这里有一个提示:尝试使用string
replace
方法。以下是方法签名:请注意,if语句中的第一个条件可以简化为:
致:
contains
方法已经返回true或false,因此不需要显式的equals比较# 4 楼答案
编辑:鉴于“.xyzxyz”应返回true,解决方案应为:
# 5 楼答案
您可以将等效的java代码用于以下解决方案:
# 6 楼答案