4

我正在制作一个 if 条件来测试给定的字符串是否在其末尾包含“me”。

Given     Return
-----     ------
Lame      True
Meant     False
Come      True
etc

现在,如果字符串长度大于 2 个字符,我的代码可以正常工作。

public boolean containsLy(String input) {
  String ly = "ly";
  String lastString = input.substring(input.length() - 2);
  if (input.length() < 2) {
      return false;
  }else if (lastString.equals(ly)) {
      return true;
  }else
      return false;
}

但每当字符串有 2 个字符或更少时,我都会收到此错误:

StringIndexOutOfBoundsException

这显然是因为一个负数,但我想不出一个解决方法。

4

4 回答 4

4

false如果您想length在输入的 小于 2 时返回,您可以在尝试对substring输入执行操作之前进行检查。

public boolean containsLy(String input) {
  if (input == null || input.length() < 2) {
      return false;
  }
  else {
     String ly = "ly";
     String lastString = input.substring(input.length() - 2);
     if (lastString.equals(ly)) {
       return true;
     }
     else {
       return false;
     }
  }
}

或者更简单:

public boolean containsLy(String input) {
      if (input == null || input.length() < 2) {
          return false;
      }
      else {
         String ly = "ly";
         String lastString = input.substring(input.length() - 2);
         return lastString.equals(ly);
      }
    }

或者,摆脱所有 if/else 变量的东西(感谢@Ingo):

public boolean containsLy(String input) {
      return input != null 
             && input.length() >= 2
             && input.substring(input.length() - 2).equals("ly");
}
于 2013-11-14T08:26:13.087 回答
2

像这样检查怎么样

boolean endsWithMe = "myteststring".endsWith("me");

如果您这样做是为了练习,那么:

伪代码:

 if length of the given string < 2 then return false
 else substring from index length - 2 to length equals "me"
于 2013-11-14T08:26:04.557 回答
0

workaround is simple.. check for the string length before performing substring of it or use the indexOf("me") to get the index and use the length to see if it is the in the position length-2.

于 2013-11-14T08:28:32.493 回答
0

不要重新发明轮子。只需使用String#endsWith()

顺便说一句,您已经发现了为什么它没有按照您的方式工作,这很了不起。但是,您仍然首先尝试获取子字符串,然后才测试它是否可能。为什么?

于 2013-11-14T08:26:15.380 回答