Workaround for StringIndexOutOfBoundsException when testing for specific characters

I make an if condition to check if the specified string contains "me" at the end.

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

At the moment, my code works fine if the string length is more than 2 characters.

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;
}

But whenever a line has 2 characters or less, I get this error:

StringIndexOutOfBoundsException

This is obviously due to a negative number, but I can't come up with a workaround for this.

+4
source share
4 answers

If you want to return falseif the lengthinput is less than 2, you can do a check before trying to perform an operation substringon your input.

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;
     }
  }
}

Or easier:

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");
}
+4

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"
+2

. String#endsWith()

, , , , . , , . ?
0

. indexOf("me") , , length-2.

0

All Articles