L1-039 古风排版 (Java)及charAt()
中国的古人写文字,是从右向左竖向排版的。本题就请你编写程序,把一段文字按古风排版。
输入格式:
输入在第一行给出一个正整数N(<100),是每一列的字符数。第二行给出一个长度不超过1000的非空字符串,以回车结束。
输出格式:
按古风格式排版给定的字符串,每列N个字符(除了最后一列可能不足N个)
输入样例:
4
This is a test case
输出样例:
asa T
st ih
e tsi
ce s
解题:
定义数组大小后,因要求“从右向左竖向排版”,则从str[0][m-1]向下填充到str[4][m],再由str[0][m-2]向下填充到str[4][m-2],依次循环填。注意:"charAt()"方法使用以及空格的单独处理。
代码如下:
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
String s=sc.nextLine();
int m,flag=0;
if (s.length() % n == 0) {
m = s.length() / n;
} else {
m= s.length() / n + 1;
}
String[][] str = new String[n][m];
for (int i = m - 1; i>= 0; i--) {
for (int j= 0; j < n; j++) {
if (flag < s.length()) {
str[j][i] = s.charAt(flag)+"";
flag++;
} else {
str[j][i] = " ";
}
}
}
for (int x= 0; x < n;x++) {
for (int y= 0;y < m; y++) {
System.out.print(str[x][y]);
}
System.out.println();
}
}
}
charAt()方法及语法
charAt():此方法用于返回位于字符串的指定索引处的字符,索引从零开始。
定义语法:
public char charAt(int index)
例如:
public class Test {
public static void main(String[] args) {
String s = "Hello world";
char result = s.charAt(4);
System.out.println(result);
}
}
输出样例:
o