同时添加两个字符串

时间:2014-06-23 04:29:02

标签: java

我想添加两个输出应该是的字符串 if string s1 =“abc”; String s2 =“xyzwert”

两个字符串的输出应为“axbyczwert”

由于

3 个答案:

答案 0 :(得分:1)

假设两个字符串的长度相同:

StringBuilder sb = new StringBuilder();
for(int i = 0; i < str1.length(); i++) {
    sb.append(str1.charAt(i)).append(str2.charAt(i));
}
String result = sb.toString();

如果一个字符串更长,你需要这样的东西:

StringBuilder sb = new StringBuilder();
int i = 0;
for(int len = Math.min(str1.length(), str2.length()); i < len; i++) {
    sb.append(str1.charAt(i)).append(str2.charAt(i));
}
if(str1.length() != str2.length()) {
    String longerStr = str1.length() > str2.length() ? str1 : str2;
    sb.append(longerStr.substring(i));
}
String result = sb.toString();

答案 1 :(得分:1)

这会对你有帮助。

//Check if s1 or s2 is longer, if s1 is longer, set maxLength as s1.length. vice versa
int maxLength = (s1.length() > s2.length()) ? s1.length() : s2.length();
//Default result string
String result = "";
//Loop through the max number of characters based on the result earlier
//Slowly add each character of both s1 and s2 to the result string starting from index0
//This will result in the alternate adding of characters from both strings
for(int i=0; i<maxLength; i++)
{
    //Check if s1 is shorter than the maxLength to prevent index out of range.
    if(i < s1.length())
    {
        result += Character.toString( s1.charAt(i) );
    }

    //Check if s2 is shorter than the maxLength to prevent index out of range.
    if(i < s2.length())
    {
        result += Character.toString( s2.charAt(i) );
    }
}
System.out.println (result);

答案 2 :(得分:-1)

此代码将执行您想要的操作:

String s1 = "abc";
String s2 = "xyzwerwer";
StringBuilder sb = new StringBuilder();
if (s1.length() > s2.length()) {
    for (int i = 0; i < s2.length(); i++) {
        sb.append(s1.charAt(i));
        sb.append(s2.charAt(i));
    }
    sb.append(s1.substring(s1.length() - (s1.length() - s2.length())));
} else {
    for (int i = 0; i < s1.length(); i++) {
        sb.append(s1.charAt(i));
        sb.append(s2.charAt(i));
    }
    sb.append(s2.substring(s2.length() - (s2.length() - s1.length())));
}
String s3 = sb.toString();
System.out.println(s3);

编辑代码以使用最新的问题。