0

I have a string and I'm trying to find out if it's a substring in another word.

For instance(pseudocode)

say I have string "pp"

and I want to compare it (using strncmp) to 

happy
apples
pizza

and if it finds a match it'll replace the "pp" with "xx"
changing the words to

haxxles
axxles
pizza

is this possible using strncmp?

ShadyBears
  • 3,955
  • 13
  • 44
  • 66
  • To elaborate: you can use a loop over the input string and `strncmp` at each position to see if you have a match. It's a little more code than the `strstr` solution, but it will work. – nneonneo Feb 10 '13 at 01:55

2 Answers2

4

Not directly with strncmp, but you can do it with strstr:

char s1[] = "happy";

char *pos = strstr(s1, "pp");
if(pos != NULL)
    memcpy(pos, "xx", 2);

This only works if the search and replace strings are the same length. If they aren't, you'll have to use memmove and potentially allocate a larger string to store the result.

nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • Thanks a lot!!! After all that cstring learning I did last semester it seems like I still have a lot more to go. I've never used strstr, nor have I used memcpy. Thanks again. – ShadyBears Feb 10 '13 at 01:52
  • It's entirely possible to use `strncmp` to achieve this - it's easier with strstr, but that's another matter. – Mats Petersson Feb 10 '13 at 01:53
  • Worth noting: even though these are strings, we don't use `strcpy` because that's meant for copying whole strings (including their null terminators). – nneonneo Feb 10 '13 at 01:53
1

Not with strncmp. You need strstr i.e.

char happy = "happy";
char *s = strstr(happy, "pp");
if (s) memcpy(s, "xx", 2);
Ed Heal
  • 59,252
  • 17
  • 87
  • 127