删除C

时间:2016-03-28 17:26:31

标签: c char buffer

您好我正在尝试删除字符串中的第一个单词。 例如:buffer = "Hello my name is Code" 实施removeToken()后,缓冲区现在应为"my name is Code"

我目前的代码给了我一个分段错误。

我有以下内容:

char *buffer = NULL;
char *buffercopy = NULL;

void startBuffer(char *inputLine) {
    int length = strlen(inputLine);
    buffer = (char *)malloc(length);
    buffercopy = (char *)malloc(length);
    strcpy(buffer, inputLine);
    strcpy(buffercopy, inputLine);
}

char *removeToken() {
    /* removes the first token from the buffer, buffer is reduced in size */
    char *token;
    char delimiters[2] = " ,";
    int origLen = strlen(buffer);
    token = strtok(buffer, delimiters);
    printf("%s \n", token);
    int p = strlen(token);
    int i = 0;
    while (buffer[i] != '\0') {
        buffer[i] = buffer[i + p];
        i++;
    }
    return buffer;
}

1 个答案:

答案 0 :(得分:1)

您的代码中存在多个问题:

你没有分配足够的内存来复制字符串,你必须为null终止符分配一个额外的字节:

void startBuffer(char *inputLine) {
    int length = strlen(inputLine);
    buffer = (char *)malloc(length + 1);
    buffercopy = (char *)malloc(length + 1);
    strcpy(buffer, inputLine);
    strcpy(buffercopy, inputLine);
}

请注意,上面的代码可以简化为:

void startBuffer(const char *inputLine) {
    buffer = strdup(inputline);
    buffercopy = strdup(inputline);
}

removeToken中,您可以使用以下内容分配分隔符字符串:

char delimiters[2] = " ,";

这是不正确的,因为您需要'\0' null终止符的第三个字节。你可以写这个:

char delimiters[] = " ,";

您只计算初始字符串的长度,而不是分隔符,第一个字符串已更改为'\0'

因此,复制循环立即停止。

您也忘记复制复制循环中的最终'\0'

以下是更正后的版本:

char *removeToken(char *buffer) {
    const char *delimiters = " ,";
    size_t i, skip;

    skip = strcspn(buffer, delimiters); /* skip the word */
    skip += strspn(buffer + skip, delimiters); /* skip the delimiters */

    for (i = 0; buffer[skip + i] != '\0'; i++) {
        buffer[i] = buffer[skip + i];
    }
    buffer[i] = '\0';

    return buffer;
}