Home > Net >  How can i iterate a loop to select if there are multiple strings
How can i iterate a loop to select if there are multiple strings

Time:06-14

If string[] a =[a1,b1,c1], string[] b =[a2,b2,c2] and string[] c = [a3,b3,c3], how can I iterate a loop to select a1, a2, a3 and b1, b2, b3 and c1, c2, c3 and print using Java

To iterate over one string:

String[] allAs = AN.split(",");
        
for (String aANo : allAs) {
    System.out.println(aANo)
}

Can anyone help? If there are three or more string then how to do this?

CodePudding user response:

Assuming that the arrays all have the same length. I also used a list to add all the arrays cause i thought you might have more arrays. What you actually need is a for loop on indexes that is what I do.

public static void main(String[] args) {
    String[] a = new String[]{"a", "b", "c"};
    String[] b = new String[]{"g", "f", "e"};
    String[] c = new String[]{"n", "m", "c"};

    List<String[]> allArrays = new ArrayList<>();
    allArrays.add(a);
    allArrays.add(b);
    allArrays.add(c);

    for (int i = 0; i < a.length; i  ) {
        String concatString = "";
        for (String[] array : allArrays) {
            concatString = concatString.concat(array[i]);
        }
        System.out.println(concatString);
    }
}

CodePudding user response:

Considering all the arrays are of same length. Then you can use a for loop to iterate and print the strings.

    for(int i = 0;i<length;i  ){
System.out.println(a[i]   ','   b[i]   ','   c[i]);
}

CodePudding user response:

Based on comments & question, it looks like you have varied length array & so in that case, something like below may be suitable:

        String a[] = { "A", "A1", "A2" };
        String b[] = { "B", "B1" };
        String c[] = { "C", "C1", "C3" };
        String aa = "";
        String bb = "";
        String cc = "";
        int length = Math.max(c.length, Math.max(a.length, b.length));
        for (int i = 0; i < length; i  ) {
            aa = a.length < (i   1) ? "" : a[i] ",";
            bb = b.length < (i   1) ? "" : b[i] ",";
            cc = c.length < (i   1) ? "" : c[i];
            System.out.println(aa   bb  cc);

        }

Output:

A,B,C
A1,B1,C1
A2,C3

CodePudding user response:

Fixed for dynamic length.

        int ablength = Math.max(a.length, b.length);
        int currlength = Math.max(ablength, c.length);
        String str = "";
        for (int i = 0; i < currlength; i  ) {
            if (i < a.length) {
                str  = a[i]   ", ";
            }
            if (i < b.length) {
                str  = b[i]   ", ";
            }
            if (i < c.length) {
                str  = c[i]   ", ";
            }
        }
        str = str.substring(0,str.length()-2);
        System.out.println(str);
  • Related