Reputation: 9326
I was wondering if it possible to mix two strings in java. Suppose I have
11111
and
22222
What would be the best way to combine them to form?
1212121212
Upvotes: 2
Views: 6897
Reputation: 41097
I wonder if the example given is intentional, i.e they all have 1 char repeated. In that case it is much simpler. If they are not, then other answers are good.
Upvotes: 1
Reputation: 10136
Here's an implementation that preserves the remainder of unequal length strings:
public static String mix(String a, String b) {
final int aLength = a.length();
final int bLength = b.length();
final int min = Math.min(aLength, bLength);
final StringBuilder sb = new StringBuilder(aLength + bLength);
for(int i = 0; i < min; i++) {
sb.append(a.charAt(i));
sb.append(b.charAt(i));
}
if (aLength > bLength) {
sb.append(a, bLength, aLength);
} else if (aLength < bLength) {
sb.append(b, aLength, bLength);
}
return sb.toString();
}
Upvotes: 2
Reputation: 597106
Yes - iterate the first string, and for each char in it, append to a builder the char in the same position from the second string (if it exists):
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str1.length(); i++) {
sb.append(str1.charAt(i));
if (str.length() > i) {
sb.append(str2.charAt(i));
}
}
return sb.toString();
Upvotes: 1
Reputation: 70701
Assuming both strings are of equal length, you could simply write a loop to go over the characters and do what you want:
String s1, s2; /* input strings */
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s1.length(); i++) {
sb.append(s1.charAt(i));
sb.append(s2.charAt(i));
}
String result = sb.toString();
Upvotes: 4