ShadyBears
ShadyBears

Reputation: 4185

using strncmp c-style string function

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?

Upvotes: 0

Views: 379

Answers (2)

nneonneo
nneonneo

Reputation: 179462

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.

Upvotes: 4

Ed Heal
Ed Heal

Reputation: 60007

Not with strncmp. You need strstr i.e.

char happy = "happy";
char *s = strstr(happy, "pp");
if (s) memcpy(s, "xx", 2);

Upvotes: 1

Related Questions