[英]Replacing a substring in a string with another substring in c using array of pointers to string
[英]extracting substring from string using pointers in 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);
您的代码有一些根本上的错误(在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 program example(input, output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.