Doesn't return expected concatenate String

PerkOne :

I improved solution for startOz task from CodingBat. I found better solution from previous one and when I tested it I got an unexpected solution in one test case.

public String startOz(String str) {
   String result = (str.indexOf('o') == 0 ? "o" : "").concat(str.indexOf('z') == 1 ? "z" : "");
   return result;
  }
// test case:
String str = "zzzz";
System.out.println("test=" + startOz(str));

I don't understand why I get empty String for result when I expected to get test=z

Michael :

str.indexOf('z') == 1 returns false because indexOf "returns the index within this string of the first occurrence of the specified character". In your case, str.indexOf('z') is zero because zero is the first occurrence.

There is a version of this method which takes an additional argument that defines which index to start from, so you could use the following to check whether Z is the second character:

str.indexOf('z', 1) == 1

That said, a better approach to this problem is probably to use charAt:

if (str.charAt(0) == 'o') //...
if (str.charAt(1) == 'z') //...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308071&siteId=1