我正在编写代码,只要字符串中有“.xyz”,它就会返回false,但是如果有没有句点的xyz,则返回true。对于大多数通过的测试除了这个:
xyzThere("abc.xyzxyz")
有没有办法修复此测试以便它也通过?我的代码如下。
public boolean xyzThere(String str) {
for (int i = 0; i < str.length() - 2; i++) {
if (str.charAt(i) == '.') {
if (str.substring(i+1, i+4).equals("xyz")) {
return false;
}
}
else if (str.substring(i, i+3).equals("xyz")) {
return true;
}
}
return false;
}
答案 0 :(得分:0)
我会使用正则表达式。如果您担心性能,请在方法外创建模式。只需写下
private boolean xyzThere(String string) {
return string.matches("xyz.*|.*[^.]xyz.*");
}
你会没事的。
答案 1 :(得分:0)
我假设您要为包含“.xyz”的任何false
返回String
,除非它还包含“xyz”。
你首先检查“.xyz” - 如果它不存在那么我们就完成了。如果它在那里然后删除所有“.xyz”并检查简单的“xyz”
public static void main(String[] args) {
System.out.println(hasXyz("abc"));
System.out.println(hasXyz("abc.xyz"));
System.out.println(hasXyz("abcxyz"));
System.out.println(hasXyz("abc.xyzxyz"));
}
public static boolean hasXyz(final String in) {
if(in.contains(".xyz")) {
final String s = in.replaceAll("\\.xyz", "");
return s.contains("xyz");
}
return true;
}
输出:
true
false
true
true