vendredi 6 septembre 2019

Determining whether either of a pair of strings ends the other string

I'm working on some codingbat tasks for class; however, I'm a bit more experienced than the rest of the class, so I've been trying to challenge myself by golfing my code down, not using loops, etc.

Currently, I'm working on the endOther challenge. The text of the challenge is as follows:

Given two strings, return true if either of the strings appears at the very end of the other string, ignoring upper/lower case differences (in other words, the computation should not be "case sensitive").

Currently, my code is as follows:

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

Which, for the most part, works. However, given a specific case (such as the following inputs: Hiabc, abcd), the code will fail. If one string is not found in the other, then foo.indexOf(bar) will return -1. This is normally okay, and to be expected; however, if two string have adjacent length values (e.g. 4 and 5) and the shorter string does not end the other string, the statement will still return -1. The five-character string cannot be found in the four-character string (return value -1), and when its length is subtracted from the four-character string, it will again return -1, compare the two values, and finally return true.

I'm trying to figure out an efficient way to except this statement. There are bulky answers - a try/catch statement, wherein a pair of -1 being compared will still return false, for example - but I don't like how bulky these are, when I'm trying to figure out how to work through the logic of these assignments as efficiently as possible.

Any input would be appreciated. I haven't been able to come up with much besides for bulky if statements and try/catch blocks that except the exact instance I mentioned, which appears to be the only issue with my code. Thanks all in advance.

Aucun commentaire:

Enregistrer un commentaire