0

Here is the condition I'm supposed to solve:

Given two strings, a and b, create a bigger string made of the first char of a, the first char of b, the second char of a, the second char of b, and so on. Any leftover chars go at the end of the result.

Here is the working code I've managed to hatch after herculean efforts:

    public String mixString(String a, String b) {
      int cut = Math.abs(a.length() - b.length());
      String end = "";

       if (cut == 0){
        for (int i = 0 ; i < a.length() ; i ++){
          end = end + a.charAt(i) + b.charAt(i);
    }
  }
  if (a.length() > b.length()){
    for (int i = 0 ; i < b.length() ; i ++){
      end = end + a.charAt(i) + b.charAt(i);
    }
    end += a.substring (a.length() - cut);
  }
  if (a.length() < b.length()){
    for (int i = 0 ; i < a.length() ; i ++){
      end = end + a.charAt(i) + b.charAt(i);
    }
    end += b.substring (b.length() - cut);
  }
  return end;

}

Thank you in advance.

Miro
  • 1
  • 1
  • 1
    Use a `StringBuilder`, see also http://stackoverflow.com/questions/1532461/stringbuilder-vs-string-concatenation-in-tostring-in-java –  Mar 25 '17 at 08:29

2 Answers2

0

I apologize, there are inconsistencies with the code I've just posted. Here is the correct version of my code:

    public String mixString(String a, String b) {
  int cut = Math.abs(a.length() - b.length());
  String end = "";

  if (cut == 0){
    for (int i = 0 ; i < a.length() ; i ++){
      end = end + a.charAt(i) + b.charAt(i);
    }
  }
  if (a.length() > b.length()){
    for (int i = 0 ; i < b.length() ; i ++){
      end = end + a.charAt(i) + b.charAt(i);
    }
    end += a.substring (a.length() - cut);
  }
  if (a.length() < b.length()){
    for (int i = 0 ; i < a.length() ; i ++){
      end = end + a.charAt(i) + b.charAt(i);
    }
    end += b.substring (b.length() - cut);
  }
  return end;
}
Miro
  • 1
  • 1
0
private String mix(String a, String b) {
    //init result data is empty (StringBuilder is good but JVM will do it)
    String end = "";
    //Travel each character of two input string in same time
    for (int i = 0; i < Math.max(a.length(), b.length()); i++) {
        //append each character of string "a" first. If index is out of lengh just append empty
        end += i < a.length() ? a.charAt(i) : "";
        //append each character of string "b" secound. If index is out of lengh just append empty
        end += i < b.length() ? b.charAt(i) : "";
    }
    return end;
}

I think this is enough for you.

dphung duy
  • 19
  • 5