我如何在java中为我正在制作的俄罗斯方 block 游戏旋转字符串数组。例如字符串数组
[
"JJJJ",
"KKKK",
"UUUU"
]
会变成
[
"UKJ",
"UKJ",
"UKJ",
"UKJ"
]
我可以使用此代码通过字符矩阵来完成此操作
public char[][] rotate(char[][] toRotate)
{
char[][] returnChar = new char[toRotate[0].length][toRotate.length];
for(int rows = 0; rows<toRotate.length; rows++)
{
for(int cols = 0; cols<toRotate[0].length; cols++)
{
returnChar[cols][toRotate.length-1-rows]=toRotate[rows][cols];
}
}
return returnChar;
}
最佳答案
使用数组字符串与您所做的类似:
public static String[] rotate(String [] toRotate)
{
String [] returnChar = new String[toRotate[0].length()];
String [] result = new String[toRotate[0].length()];
Arrays.fill(returnChar, "");
for(int rows = 0; rows<toRotate.length; rows++)
for(int cols = 0 ; cols < toRotate[rows].length(); cols++)
returnChar[cols] = returnChar[cols] + toRotate[rows].charAt(cols);
for(int i = 0; i < returnChar.length; i++)
result[i] = new StringBuffer(returnChar[i]).reverse().toString();
return result;
}
我遍历数组toRotate
上每个String
中的所有char
,连接这个字符(toRotate[rows].charAt( cols)
) 到数组 returnChar
returnChar[cols]
关于java - java中的旋转字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13635697/