本章例程
程序1.1 重排字符
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 #define MAX_COLS 20 6 #define MAX_INPUT 1000 7 8 int read_column_numbers(int columns[], int max); 9 void rearrange(char * output, char const * input, 10 int n_columns, int columns[]); 11 12 int main(void) 13 { 14 int n_columns; 15 int columns[MAX_COLS]; 16 char input[MAX_INPUT]; 17 char output[MAX_INPUT]; 18 19 n_columns = read_column_numbers(columns, MAX_COLS); 20 21 while(gets(input) != NULL){ 22 printf("Original input: %s ", input); 23 rearrange(output, input, n_columns, columns); 24 printf("Rearrange output: %s ", output); 25 } 26 27 return EXIT_SUCCESS; 28 } 29 30 int read_column_numbers(int columns[], int max) 31 { 32 int num = 0; 33 int ch; 34 35 while(num < max && (scanf("%d", &columns[num])) == 1 36 && columns[num] >= 0) 37 num += 1; 38 39 if(num % 2 != 0){ 40 puts("last column number is not paired."); 41 return EXIT_FAILURE; 42 } 43 44 while((ch = getchar()) != EOF && ch != ' ') 45 ; 46 return num; 47 } 48 49 void rearrange(char * output, char const * input, 50 int n_columns, int columns[]) 51 { 52 int col; 53 int output_col; 54 int len; 55 56 len = strlen(input); 57 output_col = 0; 58 59 for(col = 0; col < n_columns; col += 2){ 60 int nchars = columns[col+1] - columns[col] + 1; 61 62 if(columns[col] >= len || output_col >= MAX_INPUT - 1) 63 break; 64 if(output_col + nchars > MAX_INPUT - 1) 65 nchars = MAX_INPUT - 1 - output_col; 66 67 strncpy(output + output_col, input + columns[col], nchars); 68 output_col += nchars; 69 } 70 output[output_col] = '