C和C++教程中的Struts()函数

C语言和C++编程语言提供 strstr() 函数来查找或匹配另一个字符串中的字符串。例如,我们可以搜索 pof 字符串在 poftut.com 查找匹配项并返回匹配的索引号。

null

strstr()函数语法

strstr()函数具有以下语法,其中提供了两个字符串作为参数。strstr()函数区分大小写,表示大小写重要。例如 pof 是不会数学的 Pof POF 等。

const char *strstr(const char *STR1, const char *STR2)
  • `const char*strstr`是一个函数,它将返回一个指针或句柄作为匹配的char数据类型。如果没有匹配,它将返回一个空指针。
  • `const char*STR1`是搜索STR2的字符串。它是常数char指针,简单的是C和C++中的字符串。
  • `const char*STR2`是将在STR2中搜索的术语或字符串。

strstr()函数匹配示例

我们将创建一个简单的示例来搜索 poftut.com 中的字符串或字符数组 I love the poftut.com 字符串或字符数组。在C和C++字符串和char数组中开始之前,它们是相同的,只是它们的名称不同,但是在引擎盖下,它们是相同的。

/* strstr example */#include #include int main (){   //String to search in   char str1[] ="I love poftut.com web site";   //Result pointer   char *result;   //Use strstr() function to search "poftut.com"    //and store result into result variable   result = strstr (str1,"poftut.com");   //Print result to the standart output   //This will print characters from first occurence    //to the end   //output is: poftut.com web site   puts(result);   return 0;}

strstr()函数不匹配示例

在本例中,我们将给出一个搜索词或字符串与给定字符串不匹配或在给定字符串中找不到的示例。我们会搜索的 kaleinfo.com 在绳子里面 I love poftut.com web site .

/* strstr example */#include #include int main (){   //String to search in   char str1[] ="I love poftut.com web site";   //Result pointer   char *result;   //Use strstr() function to search "kaleinfo.com"    //and store result into result variable   result = strstr (str1,"kaleinfo.com");   //Create an error because result is null pointer   puts(result);   return 0;}

此示例将创建一个异常,因为结果为null,当我们尝试打印结果时,它将创建一个错误或异常。

相关文章: 如何在Windows中使用Powershell Grep或Select-String Cmdlet Grep文本文件?

使用strstr()函数替换字符串

strstr()函数的另一个有用的例子是使用它替换字符串。我们可以找到指定的字符串并用给定的新字符串替换它。我们还将使用 strncpy() 函数替换字符串。我们将使用 I love poftut.com web site 并更换 poftut.com kaleinfo.com .

/* strstr example */#include #include int main (){   //String to search in   char str1[] ="I love poftut.com web site";   //Result pointer   char *result;   //Use strstr() function to search "poftut.com"    //and store result into result variable   result = strstr (str1,"poftut.com");   //Replace kaleinfo.com with poftut.com   strncpy(result,"kaleinfo.com",12);   //Print result to the standart output   //This will print characters from first occurence    //to the end   // Output will be: kaleinfo.comeb site   puts(result);   return 0;}

PHP中的strstr()函数

使用相同的名称和语法,PHP编程语言还提供 strstr() 功能。此函数可在PHP 5.3及更高版本中使用。在下面的示例中,我们将从电子邮件地址中找到用户名并打印到字符串中。

[email protected]';$domain_name = strstr($email_address, '@');echo $domain_name; // prints @poftut.com$user_name = strstr($email, '@', true); echo $user_name; // prints name ismail?>

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享