字符串组合功能无法按预期工作

时间:2015-11-24 14:15:06

标签: java string

  

给定两个字符串s1和s2作为输入,创建一个由s1的第一个char,s2的第一个char,s1的第二个char,s2的第二个char组成的字符串,依此类推。任何剩余的字符都会出现在结果字符串的末尾。

我的方法

为了组合str1的第一个String和另一个str2的String,我从str1和str2中取出每个字符并尝试追加它。当字符串长度相等时,我得到了正确的输出.But String 1 length小于String 2 length我的输出结果不正确。

public String combine(String str1,String str2)
 {

  int l1=str1.length();
 int l2=str2.length();
 String strnew="";
 if(l1>=l2)
 {
     for(int j=0;j<l1;j++)
     {
         char c1=str1.charAt(j);
         strnew=strnew+c1;
         for(int p=j;p<=j && p<l2 ;p++) @Edit
         {
             char c2=str2.charAt(p);
             strnew=strnew+c2;
         }
     }
 }
 else
 {
     for(int j=0;j<l2;j++)
     {
         char c1=str1.charAt(j);
         strnew=strnew+c1;
         for(int p=j;p<=j && p<l1;p++)   @Edit
         {
             char c2=str2.charAt(p);
             strnew=strnew+c2;
         }
     }
 }
 return strnew;

}

输出:

       Parameters        Actual Output  Expected Output

 Pass   'abc' '123'       a1b2c3         a1b2c3

 Fail   'Hi' 'Hello'    null             HHiellot

6 个答案:

答案 0 :(得分:4)

无需使用嵌套循环。你可以像这样使用一个循环。

public static String combine(String str1,String str2) {
    String output = "";
    // Loop as long as i < as str1.length or str2.length
    for(int i = 0; i<str1.length() || i < str2.length(); ++i) {
        if(i<str1.length()) { // add the char at i to the ouput if there is a char left to take
            output += str1.charAt(i);
        }
        if(i<str2.length()) { // add the char at i to the ouput if there is a char left to take
            output += str2.charAt(i);
        }
    }
    return output;
}

输出:

a1b2c3 
Trisect

正如Bathsheba所说,最好不要在这里使用String,而是使用StringBuilder

public static String combine(String str1,String str2) {
    //Use the complete length as initial capizity
    StringBuilder output = new StringBuilder(str1.length()+str2.length()); 
    for(int i = 0; i<str1.length() || i < str2.length(); ++i) {
        if(i<str1.length()) {
            output.append(str1.charAt(i));
        }
        if(i<str2.length()) {
            output.append(str2.charAt(i));
        }
    }
    return output.toString();
}

答案 1 :(得分:3)

这是我能想到的最清晰的方式。我喜欢&#34;尾弦&#34;将作为常规算法的一部分添加。请注意空检查和StringBuilder的使用:

String combine(String s1, String s2)
    {
        if (s1 == null && s2 == null){
            return null;
        } else if (s1 == null){
            return s2;
        } else if (s2 == null){
            return s1;
        } else {
            StringBuilder sb = new StringBuilder();
            for (int pos = 0; pos < Math.max(s1.length(), s2.length()); ++pos){
                if (pos < s1.length()){
                    sb.append(s1.charAt(pos));
                }
                if (pos < s2.length()){
                    sb.append(s2.charAt(pos));
                }
            }
            return sb.toString();            
        }        
    }

我认为由于字符串不变性,对max的重复调用将被优化。但是,它仍会进行一些不必要的长度检查。

答案 2 :(得分:2)

又一种非常奇怪的循环方法:

<div class="ad-unit">
  <div class="ad-unit-large">
    <iframe width="970" height="250" src="ad.html"></iframe>
  </div>
</div>

您可以尝试here

答案 3 :(得分:1)

你可以使用不同的方法;将字符串转换为char [],就像这样

char [] arrstr1 = str1.toCharArray();

然后选择较小的数组,并在每次选择每个数组的第i个字符时迭代它。 然后,添加更大字符串的remaning字符。

编辑:添加了更多代码以便更好地解释

char [] arrstr1 = str1.toCharArray();
char [] arrstr2 = str2.toCharArray();
String res="";
int i=0;
for(; i<arrstr1.length || i<arrstr2.length ; i++){
   res+=arrstr1[i]+arrstr2[i];
}
if(arrstr1.length >i) res+= str1.substring(i);
if(arrstr2.length >i) res+= str2.substring(i);

表现不佳,但应该有效

答案 4 :(得分:1)

问题是当一个字符串比另一个字符串长时,你不会将内部循环绑定到该长度。 您可以通过在嵌套循环中添加p < l2p < l1作为停止条件以及您已经设置的内容来更正它。

    public static String combine(String str1,String str2)
    {

        int l1=str1.length();
        int l2=str2.length();
        String strnew="";
        if(l1>=l2)
        {
            for(int j=0;j<l1;j++)
            {
                char c1=str1.charAt(j);
                strnew=strnew+c1;
                for(int p=j;p<=j && p<l2;p++)
                {
                    char c2=str2.charAt(p);
                    strnew=strnew+c2;
                }
            }
        }
        else
        {
            for(int j=0;j<l2;j++)
            {
                char c1=str1.charAt(j);
                strnew=strnew+c1;
                for(int p=j;p<=j && p < l1;p++)
                {
                    char c2=str2.charAt(p);
                    strnew=strnew+c2;
                }
            }
        }
        return strnew;

    }
}

答案 5 :(得分:1)

我想你可能想尝试一下

import java.util.Scanner;

public class WordCombiner {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        String firstWord="", secondWord="", remainingLetters="", newWord = "";

        System.out.print("enter first word: ");
        firstWord = scan.nextLine();
        System.out.print("enter second word: ");
        secondWord = scan.nextLine();

        int firstWordLength = firstWord.length();
        int secondWordLength = secondWord.length();

        if(firstWordLength==secondWordLength){

            newWord = combine(firstWord,secondWord);

        }else if(firstWordLength>secondWordLength){

            remainingLetters= firstWord.substring(secondWordLength, firstWordLength);

            firstWord = firstWord.substring(0,firstWordLength-remainingLetters.length());

            newWord = combine(firstWord, secondWord,remainingLetters);

        }else{

            remainingLetters = secondWord.substring(firstWordLength,secondWordLength);

            secondWord = secondWord.substring(0,secondWordLength-remainingLetters.length());

            newWord = combine(firstWord, secondWord,remainingLetters);

        }

        System.out.print("combined word: "+ newWord);
    }

    private static String combine(String firstWord, String secondWord,
            String remainingLetters) {
        // TODO Auto-generated method stub
        return combine(firstWord, secondWord)+remainingLetters;
    }

    private static String combine(String firstWord, String secondWord) {

        String word = "";
        for(int i = 0; i<firstWord.length();i++){
            word+=firstWord.charAt(i);
            word+=secondWord.charAt(i);
        }
        return word;

    }
}

基本上,我有两个方法具有相同的名称,但参数的数量不同(方法重载)

首先,我们确定哪个词的长度最长:

如果它相等(例如,abc和123),只需调用两个字符串作为参数。

结合(ABC,123);

否则,我们将获得超长的单词,然后将其剪切以匹配较小的单词。

e.g。

TIET RSC

我们将多余的字母存储在名为remainingLetters的变量中,然后剪切最长的单词(tiet)以匹配第二个单词的长度。所以结果将如下所示:

firstWord = tie
secondWord = rsc
remainingLetters = t 

然后调用三个参数组合(firstWord,secondWord,remainingLetters)

具有三个参数的组合方法与两个参数的组合几乎相同,只是我们在末尾添加剩余的字母。

相关问题