Search code examples
javaloopsfor-loopnested-loops

Nested for loops to iterate between two strings


I'd like to, using for loops, iterate through each string and output each character turn by turn.

String a = "apple";
String b = "class";

for (int i = 0;  i < a.length() ; i++) { // - 1 because 0 = 1
    System.out.print(a.charAt(i));
    for (int j = 0; j < b.length(); j ++) {
        System.out.print(b.charAt(j));
    }
}

I'm struggling with the inner loop.

At the moment my output is as followed:

AClasspClasspClasslClasseClass

However, I'd like to achieve the following:

acplpalses

Extended Question:

How about outputting one string in reverse while the other is outputted normally?

Current Attempt:

for (int i = a.length() - 1; i >= 0; i--) {
    System.out.println(a.charAt(i));
    for (int j = 0; j < b.length(); j ++) {
        System.out.println(b.charAt(j));
    }
}

However, this simply outputs as above, just with "Apple" in reverse order in the same format as previous:

eclasslclasspclasspclassaclass

Solution

  • You don't need 2 loops as you take the same indice for both Strings


    Same Order :

    1. Simple same-size case :

      for (int i = 0; i < a.length(); i++) {
          System.out.print(a.charAt(i));
          System.out.print(b.charAt(i));
      }
      
    2. Complex different-size case :

      int minLength = Math.min(a.length(), b.length());
      for (int i = 0; i < minLength; i++) {
          System.out.print(a.charAt(i));
          System.out.print(b.charAt(i));
      }
      System.out.print(a.substring(minLength)); // prints the remaining if 'a' is longer
      System.out.print(b.substring(minLength)); // prints the remaining if 'b' is longer
      

    Different order :

    1. Simple same-size case :

      for (int i = 0; i < a.length(); i++) {
          System.out.print(a.charAt(i));
          System.out.print(b.charAt(b.length() - i - 1));
      }
      
    2. Complex different-size case :

      int minLength = Math.min(a.length(), b.length());
      for (int i = 0; i < minLength; i++) {
          System.out.print(a.charAt(i));
          System.out.print(b.charAt(b.length() - i - 1));
      }
      System.out.print(a.substring(minLength));
      System.out.print(new StringBuilder(b).reverse().substring(minLength));