首页 > 解决方案 > 确定一对字符串中的任何一个是否结束另一个字符串

问题描述

我正在为班级做一些编码任务;但是,我比班上的其他人更有经验,所以我一直在尝试通过打高尔夫球来挑战自己,而不是使用循环等。

目前,我正在处理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 块之外,除了我提到的确切实例之外,我无法想出太多东西,这似乎是我的代码的唯一问题。提前谢谢大家。

标签: javaregexstringif-statementchar

解决方案


您可以使用正则表达式和"$"符号,这意味着整个表达式的结束:

a.matches(".*" + b + "$") || b.matches(".*" + a + "$")

这是因为String#indexOf返回第一个索引,这就是为什么:

String a = "abcdabcd";
String c = "abcd";
System.out.println(a.indexOf(c) == 0);

印刷:

真的

而且您的算法将不起作用。

这个片段描述了它:

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

PS:它区分大小写,我假设您在需要时使用部分代码段:

a = a.toLowerCase(); //转换字符串 b = b.toLowerCase(); //转换字符串


推荐阅读