c - 在 C 语言中合并一行中的两个特定列
问题描述
我想从 C 语言的一行中合并两个特定的列。该行就像“hello world hello world”。它由一些单词和一些空格组成。以下是我的代码。在这个函数中,c1 和 c2 代表列的编号,数组键是合并后的字符串。但是不好跑。
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;
}
解决方案
这是一个可能的解决方案,使用strtok()
. 它可以处理任意数量的列(buf
必要时增加大小),并且如果列的顺序颠倒(即c1
> c2
),它仍然可以工作。该函数1
在成功时返回(令牌成功合并),0
否则返回。
请注意,它strtok()
修改了它的参数 - 所以我已经复制input
到一个临时缓冲区,char buf[64]
.
/*
* Merge space-separated 'tokens' in a string.
* Columns are zero-indexed.
*
* Return: 1 on success, 0 on failure
*/
int merge_cols(char *input, int c1, int c2, char *dest) {
char buf[64];
int col = 0;
char *tok = NULL, *first = NULL, *second = NULL, *tmp = NULL;
if (c1 == c2) {
fprintf(stderr, "Columns can not be the same !");
return 0;
}
if (strlen(input) > sizeof(buf) - 1) return 0;
/*
* strtok() is _destructive_, so copy the input to
* a buffer.
*/
strcpy(buf, input);
tok = strtok(buf, " ");
while (tok) {
if (col == c1 || col == c2) {
if (!first)
first = tok;
else if (first && !second)
second = tok;
}
if (first && second) break;
tok = strtok(NULL, " ");
col++;
}
// In case order of columns is swapped ...
if (c1 > c2) {
tmp = second;
second = first;
first = tmp;
}
if (first) strcpy(dest, first);
if (second) strcat(dest, second);
return first && second;
}
示例用法:
char *input = "one two three four five six seven eight";
char dest[128];
// The columns can be reversed ...
int merged = merge_cols(input, 7, 1, dest);
if (merged)
puts(dest);
另请注意,在使用时使用不同的分隔符非常容易strtok()
- 因此,如果您想使用逗号或制表符分隔的输入而不是空格,则只需在调用第二个参数时更改它。
推荐阅读
- reactjs - ReactJS Axios,web api 被多次调用
- asp.net-core - 在 Ubuntu 上部署 Web API + Blazor WASM。WASM 的完整性问题
- android - Android 模拟器在横向模式下不显示正确的图像
- javascript - 从 ionic 中的 Promise 外部访问对象
- android - 如何在 Android Studio 中使用 Mainframer 安装 Apk?
- python - 在数据框中传播特定列而不进行任何聚合?
- python - 按钮宽度和高度在 tkinter tkmacosx 中不起作用
- c# - 使 xsd.exe 实用程序生成具有强类型的架构
- scala - Scala:从列表创建二叉树
- c++ - 概念中的 C++ 值评估