0

我想用索引替换字符串。x和之间的字符串y。如果要替换长度的字符串是 lees than y,则指针必须按差值递增。例如,

给定字符串([10 20]...[10 20]..[30 80])x = 1(index of [) 和y = 7(index of ]),并且字符串替换为50,它必须替换为(50...[10 20]..[30 80])

我试过了:

void replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
{
  assert(start < end);

  char *p = s, *q = s, *r = replace;
  register unsigned int i =  0;
  int found = 0;

  while(*q) {

    if(found == 0 && i == start) {

      found = 1;

      for(; *r; ++r, ++start, ++q)
    *p ++ = *r;

      while(++start < end)
    q++;
    }

    *p ++ = *q ++;   
    i ++;
  }

}

使用:

  char str[] = "([10 20]...[10 20]..[30 80])";
  printf("Before: %s\n", str);
  replaceindex(str, "50", 1, 7);
  printf("After: %s\n", str);

输出是:

Before: ([10 20]...[10 20]..[30 80])
After: (500]...[10 20]..[30 80])0])

但我期待这个:

Before: ([10 20]...[10 20]..[30 80])
After: (50...[10 20]..[30 80])

如何解决这个问题?

4

3 回答 3

3

基于Anon ymous 的想法,但避免创建新字符串:

void replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
{
  unsigned rl, sl;
  rl = strlen(replace);
  sl = strlen(s);
  ++end; /* change inclusive index to exclusive one */
  assert(start <= end);
  assert(rl <= end - start);
  memcpy(s + start, replace, rl);
  memmove(s + start + rl, s + end, sl - end + 1);
}
于 2012-08-07T22:03:30.017 回答
0
#include <stdio.h>
#include <string.h>
 char* replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
 {

   char *rep= (char*)malloc(strlen(s)+1);
   memset(rep,0,strlen(s)+1);
   if(strlen(replace)<=(end-start))
     { memcpy(rep,s,start);
      memcpy(rep+start,replace,strlen(replace));
      memcpy(rep+start+strlen(replace),s+end,strlen(s+end));
      return rep;
    }
    else{free(rep);}
    return s;

 }


int main() {
char* z="This answer is crazy";
printf("%s",replaceindex(z,"Code",5,11));

return 0;
} 

输出是

This Code is crazy

编辑:

没有记忆:-

 #include <stdio.h>
#include <string.h>
void replaceindex(char *s, char *replace, unsigned int start, unsigned int end)
{
  if(strlen(replace)<=(end-start))
  {
  char* iter=  s+start+strlen(replace),*cursor=s+end;
  memcpy(s+start,replace,strlen(replace));
  while(*iter)
   *iter++=*cursor++;
  }
}


int main() 
{
char z[]="This answer is crazy";
replaceindex(z,"Code",5,11);
return printf("%s",z);
} 
于 2012-08-07T20:02:15.027 回答
0

您需要两个修复:

       for(; *r; ++r, ++start, ++q)
     *p ++ = *r;

-      while(++start < end)
+      while(start++ <= end)
     q++;
     }

     *p ++ = *q ++;
     i ++;
   }
+  *p = '\0';

 }

第一个是因为你的结束索引是包容性的(从调用来看),你想先比较然后增加。第二个是终止新字符串。

请注意,如果strlen(replace) > end - start + 1.

于 2012-08-07T21:57:18.090 回答