我有一个字符串,我试图找出它是否是另一个单词的子字符串。
例如(伪代码)
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
这可以使用 strncmp 吗?
不直接使用strncmp,但您可以使用strstr:
char s1[] = "happy";
char *pos = strstr(s1, "pp");
if(pos != NULL)
memcpy(pos, "xx", 2);
这仅适用于搜索和替换字符串的长度相同的情况。如果不是,您将不得不使用memmove并可能分配一个更大的字符串来存储结果。
不使用 strncmp。你需要strstr即
char happy = "happy";
char *s = strstr(happy, "pp");
if (s) memcpy(s, "xx", 2);