ThatGuy343
ThatGuy343

Reputation: 2424

Rotate a multiline string

This is a bit of an odd question, but i cant figure out how to do this. I have a multi-line string which looks like this when printed:

xxx$$xx
xxx$$xx
xxxxxxx
xxxxxxx

How can I "rotate" it 90 degrees? Desired outcome:

xxxxxxx
xxxxxxx
xxxxxxx
xxxxx$$

In my class, each line of the final output string is individually put together then appended with a line break to print the first string (multi line) above.

Upvotes: 0

Views: 164

Answers (2)

npinti
npinti

Reputation: 52185

Assuming that by rotate you do not also mean printing the text sideways, you could treat your multi line string as a 2d array of characters.

You could then do something like so:

for row in nonRotated
   for column in nonRotated[row]
       rotated[column][row] = nonRotated[row][column]

Upvotes: 4

user3480913
user3480913

Reputation:

not sure if it's already answered now but I'd do it like this:

String[][] testArr = new String[][] { { "a", "b" }, { "a", "a" },
    { "c", "c" } };

System.out.println("Array before:");
for (int i = 0; i < testArr.length; i++) {
  for (int j = 0; j < testArr[i].length; j++) {
    System.out.print(testArr[i][j]);
  }
  System.out.println();
}
//rotation start
int A = testArr.length;
int B = testArr[0].length;
String[][] arrDone = new String[B][A];
for (int i = 0; i < A; i++) {
  for (int j = 0; j < B; j++) {
    arrDone[j][A - i - 1] = testArr[i][j];
  }
}
//rotation end
System.out.println("Array afterwards:");
for (int i = 0; i < arrDone.length; i++) {
  for (int j = 0; j < arrDone[i].length; j++) {
    System.out.print(arrDone[i][j]);
  }
  System.out.println();
}

Upvotes: 1

Related Questions