繁体   English   中英

如何在Java中将两个String合并为一个String

[英]How to merge two String into one String in java

假设:

String s1="13579";
String s2="2468";

那么输出将是123456789

这是我的代码:

public class JoinString {

    public static void main(String[] args) {

        String s1 = "13579"; 
        String s2 = "2468";
        for (int i = 0; i < s1.length(); i++) {
            for (int j = i; j < s2.length(); j++) {

                System.out.print(s1.charAt(i) + "" + s2.charAt(j));
                break;
            }
        }
    }
}
StringBuilder buf = new StringBuilder();
for (int i = 0; i < Math.max(s1.length(), s2.length()); i++) {
    if (i < s1.length()) {
        buf.append(s1.charAt(i));
    }
    if (i < s2.length()) {
        buf.append(s2.charAt(i));
    }
}
final String result = buf.toString();

您只需要一个循环。 另外,您可以使用StringBuilder类逐个字符地构建字符串。

这个小把戏怎么样:

String s1 = "13579"; 
String s2 = "2468";

String s3 = (s1 + s2).codePoints() // stream of code points
    .sorted()
    // collect into StringBuilder
    .collect(StringBuilder::new, StringBuilder::appendCodePoint,  StringBuilder::append) 
    .toString();

System.out.println(s3); // 123456789 

一种简单的方法是通过执行以下操作:

String s1 = "13579"; 
String s2 = "2468";
char[]result = (s1+s2).toCharArray();
Arrays.sort(result);
System.out.println(result);

输出:

123456789

您只需要像这样组合两个循环的逻辑即可(如果您想以此方式构建字符串,请使用StringBuilder)。

    String s1 = "13579"; 
    String s2 = "2468";
    int length = Math.max(s1.length(), s2.length());
    for (int i = 0; i < length; i++) {
        if(i < s1.length())
          System.out.print(s1.charAt(i));

        if(i < s2.length())
          System.out.print(s2.charAt(i));
    }

与@Roman Puchovskiy相似,这是一种无需StringBuilder

    String s1 = "abcde";
    String s2 = "defgh";
    String combined = "";
    int length = s1.length() > s2.length() ? s1.length() : s2.length(); //Finds the longest length of the two, to ensure no chars go missing
    for(int i = 0 ; i < length ; i++) {
        if(i < s1.length()) { // Make sure there is a char in s1 where we're looking.
            combined += s1.charAt(i);
        }
        if(i < s2.length()) { // Same with s2.
            combined += s2.charAt(i);
        }
    }

combined变为合并的字符串。 "adbecfdgeh" )。

希望这可以帮助!

与合并排序中的合并方法类似。

另外,最好将字符串转换为char数组,以使对元素的随机访问处于恒定时间。 因为charAt具有O(n)时间复杂度。

public class JoinString {

public static void main( String[] args ) {

    String s1 = "13579";
    String s2 = "2468";
    final char[] str1 = s1.toCharArray();
    final char[] str2 = s2.toCharArray();
    int i;
    for ( i = 0; i < str1.length && i < str2.length; i++ ) {
        System.out.print( str1[i] + "" + str2[i] );
    }

    while ( i < str1.length ) {
        System.out.print( str1[i] + "" );
        i++;
    }

    while ( i < str2.length ) {
        System.out.print( str2[i] + "" );
        i++;
    }
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM