我正在为类做一些codingbat任务;然而,我比类其他人更有经验,所以我一直在尝试通过改进代码、不使用循环等来挑战自己。
目前,我正在处理 the endOther挑战。挑战正文如下:
给定两个字符串,如果其中一个字符串出现在另一个字符串的最末尾,则返回 true,忽略大小写差异(换句话说,计算不应“区分大小写”)。
目前,我的代码如下:
public boolean endOther(String a, String b) {
a = a.toLowerCase(); //convert string
b = b.toLowerCase(); //convert string
if((a.indexOf(b) == a.length() - b.length()) || (b.indexOf(a) == b.length() - a.length()))
//if the starting location of the second string within the first is the same
//as the difference in length between the two strings, the second string ends
//the first string
return true;
else
return false;
}
这在很大程度上是有效的。但是,在特定情况下(例如以下输入:Hiabc、abcd),代码将失败。如果在另一个字符串中找不到一个字符串,则 foo.indexOf(bar)
将返回 -1
。这通常是正常的,也是可以预料的;但是,如果两个字符串具有相邻的长度值(例如 4 和 5),并且较短的字符串没有结束另一个字符串,则该语句仍将返回 -1
。四字符字符串中找不到五字符字符串(返回值-1
),当四字符字符串减去其长度时,将再次返回-1
,比较两个值,最后返回true。
我正在尝试找出一种有效的方法来排除此语句。有大量的答案 - 例如,一个 try/catch 语句,其中一对 -1
进行比较仍将返回 false - 但当我尝试时,我不喜欢它们有多么庞大弄清楚如何尽可能有效地完成这些作业的逻辑。
如有任何意见,我们将不胜感激。除了庞大的 if 语句和 try/catch block 之外,我无法想出太多东西,除了我提到的确切实例,这似乎是我的代码的唯一问题。提前感谢大家。
最佳答案
您可以使用正则表达式和“$”
符号,这意味着整个表达式的结束:
a.matches(".*" + b + "$") || b.matches(".*" + a + "$")
这是因为 String#indexOf
返回第一个索引,这就是原因:
String a = "abcdabcd";
String c = "abcd";
System.out.println(a.indexOf(c) == 0);
打印:
true
你的算法将不起作用。
这段代码描述了它:
String a = "abcdabcd";
String b = "abc";
String c = "abcd";
System.out.println(a.matches(".*" + b + "$")); // false - doesn't match end of a, although clearly is part of it
System.out.println(a.matches(".*" + c + "$")); // true - that's what we want
System.out.println(a.indexOf(c) == 0); // true - returns lowest index
P.S.:区分大小写,我假设您在需要时使用了代码片段的一部分:
a = a.toLowerCase();//转换字符串 b = b.toLowerCase();//转换字符串
关于java - 确定一对字符串中的任何一个是否结束另一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57824802/