c - C语言合并一行中的两个特定列

标签 c string merge line multiple-columns

我想用 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)。如果成功( token 成功合并),该函数将返回 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() 时很容易使用不同的分隔符 - 因此,如果您想使用逗号或制表符分隔的输入而不是空格,只需更改第二个参数即可当调用它时。

关于c - C语言合并一行中的两个特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50838896/

相关文章:

c++ - iPhone - OpenGL 使用 C++ 教程/片段

C的怪异指针运算2

c - 从字符串 C 中读取一些数据

R:合并两个数据帧而不相乘行

c++ - 获取App路径,末尾不带应用名称

ios - 如何在 openGL ES 中将 float 组传递给纹理?

c++ - 为什么包含 '\0' 和 '\t' 的字符串不能使用 operator == 与 "\0\t"进行比较?

string - 解决局部对齐的算法

git - 从 master cherry-pick 到分支时避免重复提交,然后从分支 merge 回 master

sql - 合并到广告订单中