首页 > 解决方案 > 使用C中的指针从字符串中提取子字符串

问题描述

我目前正在尝试在缓冲线中提取子字符串。目标是通过空格和符号解析字符串以便稍后编译。我要解析的行是文件的第一行。

void append(char* s, char c)
{
    int len = strlen(s);
    s[len] = c;
    s[len+1] = '\0';
}

int main(void){    
    char str[] = "program example(input, output);";

    char *f = str;
    char *b = str;

    char token[10];

    if(*f != '\0'){
        while (*f != ' ')
        {
            append(token,*f);
            f++;
        }
        f++;
        printf("%s",token);
        token[9] = '\0';
    }
    return 0;
}

我清除令牌字符串是否错误?代码只返回:

program

但它应该返回

program
example(input,
output);

标签: cstringpointersbuffer

解决方案


您的代码存在一些根本错误(append() 函数中缓冲区溢出的可能性等)。据我了解,我所做的更改足以让代码产生所需的结果。

int main(void){    
    char str[] = "program example(input, output);";

    char *f = str;

    char *token=(char *)malloc((strlen(str)+1)*sizeof(char));
    char *b = token;

    while(*f != '\0'){
        while (*f && *f != ' ')
        {
            *b++=*f;
            f++;
        }
        if(*f) f++;
        *b=0;
        b=token;
        printf("%s\n",token);
    }
    free(token);
    return 0;
}
$ ./a.out
程序
示例(输入,
输出);


推荐阅读