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?
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.
Not with strncmp. You need strstr ie
char happy = "happy";
char *s = strstr(happy, "pp");
if (s) memcpy(s, "xx", 2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.