6
\$\begingroup\$

My problem is this: Given two strings, append them together and return the result. However, if the strings are different lengths, omit chars from the longer String so it is the same length as the shorter String. So "Hello" and "Hi" yield "loHi". The strings may be any length. Is there a way to do it without using of StringBuilder like me:

public String equalConcatenation(String a, String b) {
  if(a.length() > b.length()){
    StringBuilder sb = new StringBuilder(a);
    sb.delete(0, (a.length() - b.length()));
    return sb.toString() + b;
  }
  StringBuilder sb = new StringBuilder(b);
  sb.delete(0, (b.length() - a.length()));
  return a + sb.toString();
}
\$\endgroup\$
5
\$\begingroup\$

You're not using StringBuilder effectively. If you already have sb, then why not do sb.append(b).toString() instead of sb.toString() + b? If you look at the generated bytecode for sb.toString() + b, you'll see that it actually makes another StringBuilder for you, like new StringBuilder(sb.toString()).append(b).toString().

I would write it this way instead, with no special cases:

public static String equalConcatentation(String a, String b) {
    int len = Math.min(a.length(), b.length());
    return a.substring(a.length() - len) +
           b.substring(b.length() - len);
}

I've chosen to make it a static method because it's purely a function of the two input strings, not using any object state.

\$\endgroup\$

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.