c - 使用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 程序 示例(输入, 输出);
推荐阅读
- python - 如何用逗号替换多种类型的分隔符
- javascript - Javascript控制台输出不同的值然后在文本上
- java - 如何使用 jOOQ 修改纯 sql 文本,例如附加 order-by/limit-offset 子句或更改 where 条件值?
- csv - 如何转义csv文件中的单引号?
- python - 将多个列表值转换为多个字典中的字符串
- sql - 我自己的“字符变化”类型字段,为什么它在 pgsql 视图中是“文本”类型?
- telegram - Telegram 可以通过 id 进行聊天,不能通过 @name:Chat not found
- linux-device-driver - 如何为同一平台设备的多个实例使用单一平台驱动程序?
- html - 想让我的网站具有移动响应能力
- repast-simphony - Repast Java:创建自定义边缘代理以安排特定操作