首页 > 解决方案 > 在 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;
}

标签: cstringmergelinemultiple-columns

解决方案


这是一个可能的解决方案,使用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()- 因此,如果您想使用逗号或制表符分隔的输入而不是空格,则只需在调用第二个参数时更改它。


推荐阅读