文字竖排

 实现文字竖排
   输入字符串:长江后浪退前浪,前浪死在沙滩上。
   输出:沙前退长
            滩浪前江
            上死浪后
            。在,浪
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);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值