0

i have a substring problem in c.it is not changing the substring properly.it has to find foo and replace it with other thing but it can not changes it.it just changes the 'o' part. please help out.

#include <stdio.h>
#include <string.h>

char *replace(char *s, char old, char newer)
{
char *p = &s[0];

while(*p)
{
if(*p == old)
*p = newer;

p++;
}

return s;
}

int main()
{
char mystr[250];
printf("enter ");
gets(mystr);
puts(replace(mystr, 'foo', 'bars'));
return 0;
}
salihgueler
  • 3,284
  • 2
  • 22
  • 33
  • Your function can only replace single characters. – Jon Dec 04 '12 at 09:39
  • [This](http://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c) is what you want my friend, you want to replace strings, not individual characters. – axiom Dec 04 '12 at 09:40
  • @axiom thank you friend i will look for it.but the thing that i don't understand it why it is changing just one character?? – salihgueler Dec 04 '12 at 09:42
  • Try adding a `printf("\n%c %c\n",old,newer);` in `replace()`. When you pass the multicharacter, what actually get passed is `o` and `s` respectively (The value passed may vary depending on the implementation). Hence the problem. Also refrain from using `gets()`. I bet the compiler warns you about `gets()` too. Try using `fgets()` instead. – axiom Dec 04 '12 at 09:47
  • i tried to put fgets but it is giving me error i think it is not a big deal.but i am seeing what you see.problem is it just changes one character and couldn't fix that.damn it :D – salihgueler Dec 04 '12 at 09:53

3 Answers3

1
char *replace(char *s, char *old, char *newer)
{
...

if(*p == *old){
    *p = *newer;
    old++; newer++;
}
...

puts(replace(mystr, "foo", "bars"));

These changes should fix the problem.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
0

'foo' and 'bars' are not a chars

carlosdc
  • 12,022
  • 4
  • 45
  • 62
0

First thing, your functions takes single chars "old" and "new" but you want to replace substrings..

Oliver
  • 596
  • 1
  • 7
  • 20
  • For starters, change the signature to _char *replace(char *s, char *old, char *newer)_ and do a _strcmp_. Or check the link from @axiom at your main post. – Oliver Dec 04 '12 at 09:51