在 C 中使用指针从字符串中提取子字符串

extracting substring from string using pointers in C

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

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

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

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

    char token[10];

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

我是不是把token字符串清错了?代码只有 returns:

program

但应该 return

program
example(input,
output);

您的代码存在一些根本性错误(缓冲区溢出的可能性 在你的 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 != '[=10=]'){
        while (*f && *f != ' ')
        {
            *b++=*f;
            f++;
        }
        if(*f) f++;
        *b=0;
        b=token;
        printf("%s\n",token);
    }
    free(token);
    return 0;
}
$ ./a.out 
program
example(input,
output);