C语言:找出s1中是否存在字符串s2

Vah*_*ili 0 c char

是否有任何C函数来检查s1中是否存在字符串s2?

s1: "CN1 CN2 CN3"
s2: "CN2"  or  "CG2"
Run Code Online (Sandbox Code Playgroud)

s1是固定的,我想检查s1中是否存在s2的变体.

我使用的是C而不是C++.

Pau*_*l R 6

你可以使用strstr:

#include <string.h>

if (strstr(s1, s2) != NULL)
{
    // s2 exists in s1
}
Run Code Online (Sandbox Code Playgroud)


tao*_*ocp 5

你可以用strstr.请参阅strstr文档

function strstr

char*strstr(const char*str1,const char*str2);

查找str指向的字节字符串中第一次出现的字节字符串substr.

示例用法如下所示:

 const char *s1 = "CN1 CN2 CN3";
 if (strstr(s1, "CN2") == NULL) //^^!=NULL means exist
 {
     //does not exist
 }
Run Code Online (Sandbox Code Playgroud)