旋转多行字符串

  • 本文关键字:字符串 旋转 java
  • 更新时间 :
  • 英文 :


这是一个有点奇怪的问题,但我不知道如何做到这一点。我有一个多行字符串,打印时看起来像这样:

xxx$$xx
xxx$$xx
xxxxxxx
xxxxxxx

如何将其"旋转"90度?期望结果:

xxxxxxx
xxxxxxx
xxxxxxx
xxxxx$$

在我的类中,最终输出字符串的每一行都被单独放在一起,然后附加一个换行符来打印上面的第一个字符串(多行)。

假设旋转并不意味着横向打印文本,则可以将多行字符串视为2d字符数组。

然后你可以这样做:

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

不确定现在是否已经回答了,但我会这样做:

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

最新更新