Enigmatic
Enigmatic

Reputation: 4148

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

Upvotes: 0

Views: 2519

Answers (3)

azro
azro

Reputation: 54148

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));
    

Upvotes: 4

Anju Geetha Nair
Anju Geetha Nair

Reputation: 11

For the extended question- Assuming both strings are of same size

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

Upvotes: 1

Adam Siemion
Adam Siemion

Reputation: 16029

Another solution using Java 8 streams:

System.out.println(
    IntStream.range(0, Math.min(a.length(), b.length()))
        .mapToObj(i -> "" + a.charAt(i) + b.charAt(i))
        .collect(Collectors.joining(""))
);

Upvotes: 2

Related Questions