0
\$\begingroup\$

I solved this CodingBat problem:

Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the string unchanged. Note: use .equals() to compare 2 strings.

notString("candy") → "not candy"
notString("x") → "not x"
notString("not bad") → "not bad"

Here is the solution I came up with:

public String notString(String str) {
  if(str.indexOf("not") == 0){
    return str;
  }
  return "not " + str;
}

I was wondering how it compared to their solution:

public String notString(String str) {
  if (str.length() >= 3 && str.substring(0, 3).equals("not")) {
    return str;
  }

  return "not " + str;
}

Obviously neither is "wrong" but I was just wondering (in the long run) which has better syntax / more efficient code?

\$\endgroup\$
  • \$\begingroup\$ I am also using multiple resources to learn Java including edx.org, Head First Java, CodingBat, and more. I have learned how to approach problems in a variety of different ways, and that's why I asked for clarification here. \$\endgroup\$ – aclark Oct 6 '18 at 18:04
3
\$\begingroup\$

It should be obvious which strategy is better. Suppose you are given a very long string. Do you really want to search the entire string for "not", then realize that the match is irrelevant because it doesn't occur at the beginning? Or would you rather just examine the first three characters of the string?

Of course, the most straightforward solution uses .startsWith():

public String notString(String str) {
    return str.startsWith("not") ? str : "not " + str;
}

I don't know why they gave a hint to use .equals(). It's also a bit unclear how a string like "notary" should be handled. Treat these tutorial-challenge sites with some suspicion.

\$\endgroup\$
  • \$\begingroup\$ Thank you. Being new this is exactly the type of advice I was looking for. It shows me how an "outlying" case that I didn't think of could affect my code, and it point outs the .startsWith() method to be more concise with my code. I have the API open constantly, but I missed that method. Appreciate the straightforward tone and answer as a new "coder". \$\endgroup\$ – aclark Oct 6 '18 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.