views:

76

answers:

2

Hello,

My code is as follows:

private static ArrayList<String[]> file;

...

void method()
{
  file = new ArrayList<String[]>();
  ...
  String[] s = str.split(";");
  file.add(s);
}

In the above, str is a long String that is seperated by semicolons.

My problem is that I want to go through each array in the ArrayList and get one element from each array.

So for example if one array was "hello; are; today" and another was "how; you;" then I want to retrieve it as "hello how are you today" (ie. one element from each array).

I can't think of a way to do this.

Any help will be much appreciated.

Thanks in advance.

+1  A: 
int currentIndex = 0;
StringBuilder b = new StringBuilder();
boolean arraysHaveMoreElements = true;
while (arraysHaveMoreElements) {
    arraysHaveMoreElements = false;
    for (String[] array : file) {
        if (array.length > currentIndex) {
            b.append(array[currentIndex];
            arraysHaveMoreElements = true;
        }
    }
    currentIndex++;
}
Bozho
+1 just wrote the exact same solution
r3zn1k
A: 

That's not too difficult - under the assumption, that all rows have equal size!!

private void dumpColumnwise() {

  // generate test input
  // String[] firstRow = {"a00", "a01", "a02"};
  // String[] secondRow = {"a10", "a11", "a12"};
  String[] firstRow = "a00;a01;a02".split(";");
  String[] secondRow = "a10;a11;a12".split(";");

  List<String[]> rows = new ArrayList<String[]>();
  rows.add(firstRow);
  rows.add(secondRow);

  // get longest row
  int numberOfColumns = 0;
  for (String[] row:rows) {
    numberOfColumns = Math.max(numberOfColumns, row.length);
  }

  int numberOfRows = rows.size();
  for (int column = 0; column < numberOfColumns; colunm++) {
    for (int row = 0; row < numberOfRows; row++) {
      String[] row = rows.get(row);
      if (column < row.length) {
        System.out.printf(" %s", rows.get(row)[column]);
      }
    } 
  }
}

Room for improvement: allow input data with different row lengths. In this case you have to (1) determine the longest row and (2) test if the column index is valid for the actual row. ... done.

Andreas_D