java中将二维数组用一维数组实现的实例

    技术2022-05-19  21

    package homework;import java.util.Scanner;public class Valign2 { // 将二维数组用一维数组做,效率更高

    public static void main(String[] args) {  System.out.println("请输入文字:");  Scanner console = new Scanner(System.in);  String str = console.nextLine();  System.out.println("请输入数字:");  int size = console.nextInt();  System.out.println(valign(str, size)); } /**  * 将一字符串,在指定位置折行竖排  *   * @param str  *            需要输入一字符串  * @param size  *            需要输入一个数字  * @return 返回一个竖排的字符串  */ public static String valign(String str, int size) {  int rows = size;// 行  int cols = str.length() % size == 0 ? str.length() / size : str    .length()    / size + 1;// 列  int idx = 0;  char[] chs = new char[cols * rows];  // 将字符填到数组中  for (int i = cols - 1; i >= 0; i--) {   for (int j = 0; j < rows; j++) {    if (idx == str.length()) {// 字符串内容读完了     chs[j * cols + i] = '~';//剩下的用'~'填充    } else {     chs[j * cols + i] = str.charAt(idx++);// 这是将二维转一维    }   }  }  // 输出  String s = "";  for (int i = 0; i < chs.length; i++) {   s += chs[i];   if ((i + 1) % cols == 0) {    s += '/n';   }  }  return s; }}


    最新回复(0)