#include <stdio.h> #include <stdlib.h> #include<string.h> #define MAXCOLS 20 #define MAXINPUT 1000 int ReadColumnNumbers(int columns[], int Max); void rearrange(char*output, char const *input, int nColumns, int const columns[]); int main(void) { int nColumns; int columns[MAXCOLS]; char input[MAXINPUT]; char output[MAXINPUT]; /*读取该串列标号*/ nColumns = ReadColumnNumbers(columns, MAXCOLS); while (gets(input) != NULL) { printf("Original input:%s\n", input); rearrange(output, input, nColumns, columns); printf("Rearranged line:%s\n", output); } return EXIT_SUCCESS; } int ReadColumnNumbers(int columns[],int Max) { int num=0; int ch; while(num<Max&&scanf("%d",&columns[num])==1&&columns[num]>=0) num+=1; /*确认标号为偶数个*/ if(num%2!=0) { puts("Last column number is not paired."); exit(EXIT_FAILURE); } /*丢弃该行包含最后一个数字那部分内容*/ while((ch=getchar())!=EOF&&ch!='\n') ; return num; } void rearrange(char*output, char const *input, int nColumns, int const columns[]) { int col; int outputCol; int len; len=strlen(input); outputCol=0; /*处理每对列标号*/ for(col=0; col<nColumns; col+=2) { int nchars=columns[col+1]-columns[col]+1; /*若输入行借书或输入行已满,即结束*/ if(columns[col]>=len||outputCol==MAXINPUT-1) break; /*若空间不够,只复制可容纳的数据*/ if(outputCol+nchars>MAXINPUT-1) nchars=MAXINPUT-outputCol-1; /*复制相关数据*/ strncpy(output+outputCol,input+columns[col],nchars); outputCol+=nchars; } output[outputCol]='\0'; }
[CHAPTER 01] 1.1 字符重排
最新推荐文章于 2019-03-03 08:32:02 发布