一个java程序,使得第一个字符串中的一个字符与第二个字符串中的一个字符从左到右连接起来

时间:2014-11-28 17:51:17

标签: java string

编写一个Java程序,该程序将两个字符串作为用户的输入。然后程序创建另一个字符串 这样第一个字符串中的一个字符与第二个字符串中的一个字符从左到右连接起来 如下图所示:

例子1:

First Input String: Hello Hi

Second input String: World of Mine

Output String: HWeolrllodHoif Mine

2 个答案:

答案 0 :(得分:1)

在循环中迭代这两个:

String s1 = "Hello Hi";
String s2 = "World of Mine";
StringBuilder result = new StringBuilder (s1.size() + s2.size());

int minLength = Math.min (s1.size(), s2.size());
for (int i = 0; i < minLength; ++i) {
    result.append(s1.charAt(i)).append(s2.charAt(i));
}
if (s1.size() > minLength) {
    result.append(s1.substring(minLength));
} else if (s12.size() > minLength) {
    result.append(s2.substring(minLength));
}

答案 1 :(得分:1)

这是一个扩展您自己的代码的解决方案(带有解释)。在您的作业中使用之前,请尝试理解代码。

public static String concateAndAppend(String data1, String data2) {
    char[] str1 = data1.toCharArray();
    char[] str2 = data2.toCharArray();
    String result = "";

    //we must iterate to the length of the smaller string
    //if you don't calculate the smaller size you might
    //get indexOutOfBounds Exceptions, i.e. you try to access
    //non-existant indexes in the arrays
    int minimum = Math.min(str1.length, str2.length); //calculate minimum between the two array lenghts

    //append the characters on the same index to the result
    //starting with str1 from left
    for (int i = 0; i < minimum; i++) {
        result = result + str1[i] + str2[i];
    }

    //now you must pad the results to include the bigger string
    //since you only iterated minimum index positions.

    //check which string is bigger then append accordingly
    if (str1.length > minimum) {
        result = result + data1.substring(minimum); //substring to only append the part after the minimum index
    } else if (str2.length > minimum) {
        result = result + data2.substring(minimum);//substring to only append the part after the minimum index
    }

    return result;
}

public static void main(String[] args) {

    String s1 = "Hello Hi";
    String s2 = "World of Mine";

    System.out.println(concateAndAppend(s1, s2));
}