实现文字竖排
输入字符串:长江后浪退前浪,前浪死在沙滩上。
输出:沙前退长
滩浪前江
上死浪后
。在,浪
输入字符串:长江后浪退前浪,前浪死在沙滩上。
输出:沙前退长
滩浪前江
上死浪后
。在,浪
package self.temp8;
import java.util.*;
public class VerticalType {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.println("输入要竖排的字符串:");
String str = cin.nextLine(); // 输入一个字符串
System.out.println("输入竖排的字符串的列数:");
int col = cin.nextInt(); // 输入一个整数
System.out.println("结果为:");
valign(str, col);
}
public static void valign(String txt, int charPerCol) {
int index = 0;
int len = txt.length(); // 得到字符串的长度
int row = len / charPerCol; // 求出竖排的行数
if (len % charPerCol != 0)
row++; // 如果不整除,行数加1
char[] arr[] = new char[row][charPerCol]; // 定义一个row行,charPerCol列的二维数组
char[] temp = new char[row * charPerCol]; // 定义字符数组的长度
Arrays.fill(temp, '*'); // 初始化填充为*
// temp = txt.toCharArray();
System.arraycopy(txt.toCharArray(), 0, temp, 0, txt.length()); // 字符串拷贝
for (int i = charPerCol - 1; i >= 0; i--)
for (int j = 0; j < row; j++)
arr[j][i] = temp[index++]; // 利用一位数组和二维数组之间的关系,初始化二维数组
/* 输出竖排后的字符串 */
String s = "";
for (int i = 0; i < row; i++) {
for (int j = 0; j < charPerCol; j++)
s += arr[i][j];
s += "\n";
}
System.out.println(s);
}
}