【发布时间】:2018-06-13 13:47:38
【问题描述】:
我想在 C 语言中合并一行中的两个特定列。该行就像“hello world hello world”。它由一些单词和一些空格组成。以下是我的代码。在这个函数中,c1 和 c2 代表列的编号,数组 key 是合并后的字符串。但是不好跑。
char *LinetoKey(char *line, int c1, int c2, char key[COLSIZE]){
char *col2 = (char *)malloc(sizeof(char));
while (*line != '\0' && isspace(*line) )
line++;
while(*line != '\0' && c1 != 0){
if(isspace(*line)){
while(*line != '\0' && isspace(*line))
line++;
c1--;
c2--;
}else
line++;
}
while (*line != '\0' && *line != '\n' && (isspace(*line)==0))
*key++ = *line++;
*key = '\0';
while(*line != '\0' && c2 != 0){
if(isspace(*line)){
while(*line != '\0' && isspace(*line))
line++;
c2--;
}else
line++;
}
while (*line != '\0' && *line != '\n' && isspace(*line)==0)
*col2++ = *line++;
*col2 = '\0';
strcat(key,col2);
return key;
}
【问题讨论】:
-
我建议编写一个自己的函数,只需在行内返回一个字符串指针和一个长度,即可将您的行拆分为单个标记(列)。然后在你的 LinetoKey 实现中使用这个函数。这降低了代码的复杂性。分别测试和组合这两个函数。
-
使用
(char *)malloc(sizeof(char));,您只会为单个字符分配内存——因此当您向col2写入多个字符时,您将写入未分配的内存。 -
“这条线就像“hello world hello world””预期的输出是什么?
-
@ZDF: 如果
c1是0并且c3是3我假设预期的输出是"helloworld"。
标签: c string merge line multiple-columns