Java 如何从两个等长的输入字符串中获取交替字符来构建字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22919096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:00:09  来源:igfitidea点击:

How to build a string taking alternate characters from two equal length input strings?

javastring

提问by IT_Philic

My Question is-

我的问题是——

Given two strings s1 and s2 of equal length as input, the expected output is a string which the 1st char from s1, then 1st char from s2, then 2nd char from s1, then 2nd char from s2 and so on. For e.g. if s1=”Outer”, s2 = “Space”, the output is “OSuptaecre”.

给定两个长度相等的字符串 s1 和 s2 作为输入,预期输出是一个字符串,其中第一个字符来自 s1,然后是来自 s2 的第一个字符,然后是来自 s1 的第二个字符,然后是来自 s2 的第二个字符,依此类推。例如,如果 s1=”Outer”, s2 = “Space”,则输出为“OSuptaecre”。

I have done it with loops and I want to know if there is any other simple code for this program like use of string functions.

我已经用循环完成了,我想知道这个程序是否还有其他简单的代码,比如使用字符串函数。

public class JoinChars {

    static String testcase1 = "Right";
    static String testcase2 = "Wrong";

    public static void main(String args[]){
        JoinChars testInstance= new JoinChars();
        String result = testInstance.join(testcase1,testcase2);
        System.out.println(result);
    }

    public String join(String str1, String str2){
        String str3="";
        if(str1.length()>=str2.length()){
            for(int i=0;i<str1.length();i++){
                str3+=str1.charAt(i);
                for(int j=i;j<str2.length();){
                    str3+=str2.charAt(j);
                    break;
                }
            }
        }
        else if(str2.length()>=str1.length()){
            for(int i=0;i<str2.length();i++){
                str3+=str2.charAt(i);
                for(int j=i;j<str1.length();){
                    str3+=str1.charAt(j);
                    break;
                }
            }
        }
        return str3;
    }
}

回答by CMPS

You mean something like this ?

你的意思是这样的?

String result = "";
for(int i=0; i<s1.length();i++){
  result += s1.charAt(i);
  result += s2.charAt(i);
}
return result;

Please note that s1 and s2 are two String input of equal length.

请注意,s1 和 s2 是两个等长的 String 输入。

回答by fge

You can largely simplify this code by a creative use of CharBuffers:

您可以通过创造性地使用CharBuffers来大大简化此代码:

public static String join(final String s1, final String s2)
{
    final int len1 = s1.length(), len2 = s2.length();
    final CharBuffer buf1 = CharBuffer.wrap(s1);
    final CharBuffer buf2 = CharBuffer.wrap(s2);
    final CharBuffer longest = len1 > len2 ? buf1 : buf2;
    final StringBuilder sb = new StringBuilder(len1 + len2);
    final int minlen = Math.min(len1, len2);

    for (int i = 0; i < minlen; i++) 
        sb.append(buf1.get()).append(buf2.get());

    return sb.append(longest).toString();
}

回答by Frakcool

public String join(String str1, String str2){
    String str3="";
    if(str1.length()>=str2.length()){
        for(int i=0;i<str1.length();i++){
            str3 += s1.charAt(i);
            str3 += s2.charAt(i);
        }
    }
    else if(str2.length()>=str1.length()){
        for(int i=0;i<str2.length();i++){
            str3 += s1.charAt(i);
            str3 += s2.charAt(i);
        }
    }
    return str3;
}

That's easier

那更容易

回答by Valentin

Here is a solution inspired by Alexis C., whose solution was good but he decided to delete it instead of editing it when I asked him why he used char arrays instead of working on the plain strings and before I had a chance to tell him he could edit his answer:

这是一个受Alexis C.启发的解决方案,他的解决方案很好,但是当我问他为什么使用 char 数组而不是处理纯字符串时,他决定删除它而不是编辑它,并且在我有机会告诉他他之前可以编辑他的答案:

public static String join(String str1, String str2) {
    int length1 = str1.length();
    int length2 = str2.length();
    int commonLength = Math.min(length1, length2);

    StringBuilder mixedStringBuilder = new StringBuilder(length1 + length2);
    // Append the characters which both strings have, mixing them
    for (int i = 0; i < commonLength; i++) {
        mixedStringBuilder.append(str1.charAt(i)).append(str2.charAt(i));
    }

    // Append the remaining characters
    mixedStringBuilder.append(str1, commonLength, length1).append(str2, commonLength, length2);

    return mixedStringBuilder.toString();
}

It works with strings of equal size as well as for strings of differing sizes.

它适用于相同大小的字符串以及不同大小的字符串。

Here are some execution examples:

以下是一些执行示例:

join("one", "TWO")          -> "oTnWeO"
join("BANANA", "apple")     -> "BaApNpAlNeA"
join("ORANGE", "pineapple") -> "OpRiAnNeGaEpple"

回答by user7839057

Pass two strings str1 and str1 of any length as input, the expected output is a string which takes the 1st char from str1, then 1st char from str2, then 2nd char from str1 and 2nd char from str2 and so on. For e.g. if str1=”Outer”, str2= “Space”, the output is “OSuptaecre”.

传递任意长度的两个字符串 str1 和 str1 作为输入,预期输出是一个字符串,它从 str1 获取第一个字符,然后从 str2 获取第一个字符,然后从 str1 获取第二个字符,从 str2 获取第二个字符,依此类推。例如,如果 str1=”Outer”,str2=“Space”,则输出为“OSuptaecre”。

//A function with two input parameter str1 and str2.
public static String stringConcate(String str1,String str2){
        //Creating a empty String variable that store the output String.
        String str3="";
        //Checking the input String is a valid String or not(It must not be empty or null).
        if(str1!=null && str2!=null && !str1.isEmpty() && !str2.isEmpty()){
               //Condition for, if both input String are of same size.
                if(str1.length()==str2.length()){
                    for(int i=0;i<=str1.length()-1;i++){
                        str3+=str1.charAt(i);
                        str3+=str2.charAt(i);

                    }
                }
                //Condition for, if str1 is greater than str2.
                if(str1.length()>str2.length()){
                    for(int i=0;i<=str1.length()-1;i++){
                        str3+=str1.charAt(i);
                        if(i<str2.length()){
                            str3+=str2.charAt(i);
                        }
                    }
                }
                //Condition for, if str1 is smaller than str2.
                if(str2.length()>str1.length()){
                    for(int i=0;i<=str2.length()-1;i++){
                        if(i<str1.length()){
                            str3+=str1.charAt(i);
                        }
                        str3+=str2.charAt(i);
                    }
                }
            }
            return str3;

    }

回答by Mark Fernandes

just to add on to the question, if the strings are of different lengths. Use recursion until one of the substring is of length 1 which implies that we need to blindly copy the other substring and return. The time complexity is O(length of the smallest string)

只是为了补充问题,如果字符串的长度不同。使用递归直到其中一个子串的长度为 1,这意味着我们需要盲目地复制另一个子串并返回。时间复杂度为O(最小字符串的长度)

public static String alternate(String str1, String str2)
{
    String result= null;

    char first= str1.charAt(0);
    char second= str2.charAt(0);

    result= Character.toString(first )+ Character.toString(second);
    if(str1.length()>1 && str2.length()>1)
        result= result+ alternate(str1.substring(1),str2.substring(1));
    else if(str1.length()==1)
        return result+str2.substring(1);
    else if (str2.length()==1)
        return result+str1.substring(1);    

    return result;

}

Do let me know if my analysis is correct. Thanks.

请让我知道我的分析是否正确。谢谢。

EDIT

编辑

str1= input()
str2= input()

str3= str1+str2

result=''
loop_length= min(len(str1),len(str2))

for i in range(0,loop_length):
    result= result+str1[i]+str2[i]

if (len(str1)>len(str2)):
    result= result+str1[(loop_length):(len(str1))]
else:
    result= result+str2[(loop_length):(len(str2))]

print(result)   

The above, I have tried in Python. This solution is easier to understand compared to my earlier java code.

以上,我已经在Python中试过了。与我之前的 java 代码相比,这个解决方案更容易理解。

回答by ROHIT KISHOR TRIPATHI

//Program to merge alternate characters of 2 Strings

//程序合并2个字符串的交替字符

public class MergedString {

  public static String getMergedString(String a,String b){
    String mergedString="";
    for(int i=0;i<a.length();i++){
        mergedString=mergedString+a.charAt(i);
        if(i<b.length()){
            mergedString=mergedString+b.charAt(i);
          }         
    }
    if(a.length()<b.length()){
        mergedString=mergedString+b.substring(a.length());
    }
    return mergedString;
  }
  public static void main(String[] args) {
    String ms=getMergedString("abcd","xyztkhj");
    System.out.print("Merged String:"+ms);

  }
}

回答by Praveen Gundu

public class Merge{

/**
 * @param args
 */
public static void main(String[] args) {
    String a ="abc";
    String b ="def";
    StringBuilder sb = new StringBuilder();
    int alength = a.length();
    int belnth = b.length();
    if(alength==b.length()){
        for(int i=0;i<belnth;i++){
            sb.append(a.charAt(i));
            sb.append(b.charAt(i));
        }           
    }else if(alength>belnth){
        int j=0;
        for(j=0;j<belnth;j++){
            sb.append(a.charAt(j));
            sb.append(b.charAt(j));
        }   
        for(j=belnth;j<alength;j++){
            sb.append(a.charAt(j));
            //sb.append(b.charAt(j));
        }

    }else if(alength<belnth){
        int j=0;
        for(j=0;j<alength;j++){
            sb.append(a.charAt(j));
            sb.append(b.charAt(j));
        }   
        for(j=alength;j<belnth;j++){
            sb.append(b.charAt(j));
            //sb.append(b.charAt(j));
        }

    }
    System.out.println(sb.toString());
}
}

回答by Saurabh Garg

This will work for both equal size and unequal

这将适用于相等大小和不相等

public static String appendAlterChar(String a, String b) {
        String res ="";
        if(a.length()>=b.length()) {
            int j=0;
            for(int i=0;i<a.length();i++){
                res+=a.charAt(i);
                while(j<b.length()){
                res+=b.charAt(i);
                j++;
                break;
                }

            }
        }
        else if(a.length()<b.length()) {
            int j=0;
            for(int i=0;i<b.length();i++){
                while(j<a.length()) {
                    res+=a.charAt(j);
                    j++;
                    break;
                }
                res+=b.charAt(i);
            }

        }

        return res;

    }

回答by Ajay Singh Meena

Concat two strings of any length alternative characters from each.

从每个字符串中连接两个任意长度的替代字符的字符串。

public class StringConcat
{
  public static void main(String [] args)
  {
    String s1 = "Ajay S";
    String s2 = "Meena AM";
    StringBuffer sb1 = new StringBuffer();
    StringBuffer sb2 = new StringBuffer();

    for(int i=0;i<s1.length() || i<s2.length();i++)
    {

        /****No Condition *****/
        if(i<s1.length())
            sb1.append(s1.charAt(i));
        if(i<s2.length())
            sb1.append(s2.charAt(i));
    }

    for(int i=0, j=0 ;i<s1.length() || j<s2.length();i++,j++)
    {

        /******Escape Space Pick Up next char ******/
        if(i<s1.length())
        {
            if(s1.charAt(i)!=32)
                sb2.append(s1.charAt(i));
            else
                sb2.append(s1.charAt(++i));
        }

        if(j<s2.length())
        {
            if(s2.charAt(j)!=32)
                sb2.append(s2.charAt(j));
            else
                sb2.append(s2.charAt(++j));
        }           
    }

    System.out.println(s1+", "+s2+" ==> "+sb1);
    System.out.println(s1+", "+s2+" ==> "+sb2);     
  }
 }