在每个子字符串实例中添加一个char

时间:2014-11-08 15:10:55

标签: c string

在我的下面的代码中,我添加了" d"在第一次" foo"在给定的字符串。我怎样才能为" 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);  
 }

2 个答案:

答案 0 :(得分:0)

使用while循环而不是if(ptr!= NULL)。像这样:

void main()
 {
    char haystack[20]="foofoofoofoo",*ptr=haystack,*temp=NULL,*temp1=NULL,needle[]="foo";
    int position,length=strlen(needle);
ptr=strstr(haystack,needle);

while (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);
        free(temp);  // free as soon as finished with it
        printf("\n%s",haystack);  
        ptr=strstr(ptr+length,needle);  // search again from position 'length' 
                                        // further into the current position in the string
                                        //  or if its not found, then ptr will be NULL
                                        //ptr+=length;
  }
}

不要忘记释放任何动态分配的变量,如temp。我没有编译它来测试它 - 但我认为你会得到这个想法

此外,您可以通过减去指针来获得找到字符串的位置。即

position= ptr - haystack; // gives 0 based 'index'

答案 1 :(得分:0)

正如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