在我的以下代码中,我在给定字符串中的第一个“foo”之后添加了“d”。我怎样才能对“foo”的其他实例做同样的事情? 任何帮助表示赞赏。
相关代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char haystack[20]="foofoofoofoo",*ptr=haystack,*temp=NULL,*temp1=NULL,needle[]="foo";
int position,length=strlen(needle);
ptr=strstr(haystack,needle);
if(ptr!=NULL)
{
temp=(char *)calloc(strlen(haystack)+100,sizeof(char));
position=(strstr(haystack,needle)-haystack);
strncpy(temp,haystack,position+length);
strcat(temp,"d");
strcat(temp,strstr(haystack,needle)+length);
strcpy(haystack,temp);
ptr+=length;
}
printf("\n%s",haystack);
}
最佳答案
正如 Grantly 所建议的,如果过一段时间你就必须改变自己。
但是:
- 您还应该在循环外部分配
temp
- 您应该释放已分配的内容
- 你应该搜索你停止的地方,而不是从头开始
它可以给出:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
char haystack[20]="foofoofoofoo",*ptr=haystack,*temp=NULL,*temp1=NULL,needle[]="foo";
int position,length=strlen(needle);
temp=(char *)calloc(strlen(haystack)+100,sizeof(char));
while(*ptr != '\0')
{
ptr=strstr(ptr,needle);
if (ptr == NULL) break;
position=ptr-haystack;
strncpy(temp,haystack,position+length);
temp[position + length] = '\0';
strcat(temp,"d");
strcat(temp,ptr+length);
strcpy(haystack,temp);
ptr+=length + 1;
}
printf("\n%s",haystack);
free (temp);
}
输出符合预期:foodfoodfoodfood
关于c - 在子字符串的每个实例中添加一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26818526/