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();
}
Phrancis
20.5k6 gold badges69 silver badges155 bronze badges
asked Dec 12, 2015 at 8:10
\$\endgroup\$

1 Answer 1

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.

answered Dec 12, 2015 at 8:32
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.