中国的古人写文字,是从右向左竖向排版的。本题就请你编写程序,把一段文字按古风排版。
输入格式:
输入在第一行给出一个正整数N(<100),是每一列的字符数。第二行给出一个长度不超过1000的非空字符串,以回车结束。
输出格式:
按古风格式排版给定的字符串,每列N个字符(除了最后一列可能不足N个)。
输入样例:
4
This is a test case
结尾无空行
输出样例:
asa T
st ih
e tsi
先上答案 :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char str[10001];char* p=str;
int n,lie,count=0;
//输入:getchhr抵消回车,gets能读取有空格的字符串而scanf不行
scanf("%d",&n);
getchar();
gets(str);
//计算有多少列
if(strlen(str)%n>0)
lie = strlen(str)/n+1;
else
lie = strlen(str)/n;
//赋值 --但是字符串最后一个是\0,所以用空格重写
char s[n][lie];
for(int i=lie-1;i>=0;i--){
for(int j=0;j<n;j++){
if(count==strlen(str))
s[j][i]= ' ';
else {
s[j][i]=*p;
if(count!=strlen(str)){
count++;p++;
};
}
}
}
//打印
for(int i=0;i<n;i++){
for(int j=0;j<lie;j++)
printf("%c",s[i][j]);
printf("\n");
}
}
注释:
1.给二维数组的赋值我是用了指针的自增,注意第一个for是列,第二个是行
2.里面的if语言在strlen(str)就用空格覆盖是因为字符串最后一个是“\0"很坑!!count用来记录指针的偏移量