c语言重排字符,程序1.1 重排字符 (rearrange.c)

/*

** 这个程序从标准输入(键盘)中读取输入行并按需求处理后在标准输出(屏幕)中打印,

** 每个输入行的后面一行是该行按需求处理后的输出内容。

**

** 输入的第1行是一串列标号,串的最后以一个负数结尾。

** 这些列标号成对出现,说明需要打印的输入行的列的范围。

** 例如,0 3 10 12 -1 表示第0列到第3列,第10列到第12列的内容将被打印。

*/

#include

#include

#include

#define MAX_COLS 20/* 所能处理的最多列标号数量 */

#define MAX_INPUT 1000/* 所能处理的最大输入行长度 */

int read_column_numbers(int columns[], int max);

void rearrange(char *output, char const *input, int n_columns, int const columns[]);

int main(void)

{

int n_columns;/* 记录君:实际读取的列标号个数 */

int columns[MAX_COLS]; /* 容器君:实际读取的列标号们 */

char input[MAX_INPUT];/* 容器君:输入行字符串 */

char output[MAX_INPUT];/* 容器君:输出行字符串 */

/*

** 读取该串列标号并统计个数

*/

n_columns = read_column_numbers(columns, MAX_COLS);

/*

** 读取、处理和打印剩余的输入行

*/

while(gets(input) != NULL)

{

printf("原始输入: %s\n", input);

rearrange(output, input, n_columns, columns);

printf("截取输出: %s\n", output);

}

return EXIT_SUCCESS;

}

/*

** 读取列标号(存入数组),超出规定范围(2)则不予理会

**

** 参数表: columns 列标号存储用数组

**max 数组最大容量

**

** 返回值:num实际读取的列标号个数

*/

int read_column_numbers(int columns[], int max)

{

int num = 0;/* 计数君:当前已读入列标号的数量 */

int end_ch;/* 记录君:结束字符 */

/*

** 读入列标号,如果所读取的数小于0则停止

*/

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);

}

/*

** 丢弃超出的列标号,防止被解释为第1行数据

*/

while( (end_ch = getchar()) != EOF && end_ch != '\n' )

;

return num;

}

/*

** 处理输入行,将指定列的字符连接在一起,输出行以NUL结尾

*/

void rearrange(char *output, char const *input, int n_columns, int const columns[])

{

int i;/* 计数君:columns 数组的下标 */

int len;/* 记录君:输入行的长度 */

int out_emp_i;/* 计数君:输出数组可用空间首位置下标 */

len = strlen(input);

out_emp_i = 0;/* bug:忘记初始化 */

/*

** 处理每对列标号

*/

for(i = 0; i < n_columns; i += 2)

{

int nchars = columns[i+1] - columns[i] + 1;/* 本次写入输出的字符数 */

/*

** 如果输入行结束或输出行数组已满,则结束任务

*/

if(columns[i] >= len || out_emp_i == MAX_INPUT - 1)

{

break;

}

/*

** 如果输出行数据空间不够,只复制可以容纳的数据

*/

if(out_emp_i + nchars > MAX_INPUT - 1)

{

nchars = MAX_INPUT - 1 - out_emp_i;

}

/*

** 复制相关的数据 (赞指针偏移的用法)

*/

strncpy(output + out_emp_i, input + columns[i], nchars);

out_emp_i += nchars;

}

output[out_emp_i] = '\0';

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值