Why arrayC store only one element from each array?
I planned to mix 2 lines.

 public static void mixString(String a, String b) { String[] arrayA = a.split(""); String[] arrayB = b.split(""); String[] arrayC = new String[a.length() + b.length()]; for (int i = 0; i < arrayC.length - 1; i++) { getTurn(); if (f) { for (int j = 0; j < arrayA.length; j++) arrayC[i] = arrayA[j]; } else { for (int x = 0; x < arrayB.length; x++) arrayC[i] = arrayB[x]; } } } public static boolean getTurn() { f = !f; return f; } 
  • one
    because you always put only the last element from other arrays in the cell arrayC - Alexey Shimansky
  • Why, Sklifosovsky? - OldHuman
  • Because you asked so))) - Alexey Shimansky
  • Oooh ... I feel better - OldHuman

3 answers 3

 public static void mixString(String a, String b) { char[] arrayC = new char[a.length() + b.length()]; int idxA = 0; int idxB = 0; for (int i = 0; i < arrayC.length; i++) { if (idxB >= b.length() || (idxA < a.length() && getTurn())) arrayC[i] = a.charAt(idxA++); else arrayC[i] = b.charAt(idxB++); } } 

    Splitting a string into an array of strings using split to work with specific characters of the string is a very suboptimal option. To do this, in the class String there is a method charAt (int index) .

    To work with a character set in this case, it is better to use an array of char[] characters, rather than an array of strings String[] , consisting of one character.

    To create a string from an array of characters, there is a method String.valueOf (char [] data) .

    The result is the following code:

     public static String mixString(String a, String b) { char[] resultChars = new char[a.length() + b.length()]; for (int i = 0; i < resultChars.length; i++) { resultChars[i] = (i % 2 == 0) ? a.charAt(i / 2) : b.charAt(i / 2); } return String.valueOf(resultChars); } 
    • Thanks, buddy! - OldHuman

    By writing

     for (int j = 0; j<arrayA.length; j++) arrayC[i] = arrayA[j]; 

    the loop executes a number of times equal to arrayA.length In arrayA each element from arrayA is placed permanently in the same cell of arrayC[i] . As a result, when the loop ends in a cell, only the last element of the array is found. And so constantly.

    Similarly with arrayB

    • Why is i ++ not working? - OldHuman
    • @OldHuman why, it works ..... you run through arrayC but at the same time only the last element of another array gets into each cell, because always the second cycles are idling putting only the last element into the arrayC[i] cell - Alexey Shimansky
    • Thank you, damn I'm such a horse (( - OldHuman
    • @OldHuman with all happens. Just read the information about debugging applications and then you don’t have to constantly ask such questions on the forums and you can track the execution of your program line by line. - Alexey Shimansky