学堂 学堂 学堂公众号手机端

在C++中,strstr函数用于在一个字符串中搜索指定子字符串的位置

lewis 1年前 (2024-03-19) 阅读数 3 #技术

在C++中,strstr函数用于在一个字符串中搜索指定子字符串的位置。其原型如下:

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

其中,str1是要搜索的字符串,str2是要查找的子字符串。strstr函数会返回指向第一次出现str2的位置的指针,如果找不到则返回nullptr

示例代码:


#include<iostream> #include<cstring> intmain(){ constchar*str1="Hello,world!"; constchar*str2="world"; char*result=strstr(str1,str2); if(result){ std::cout<<"Foundatposition:"<<result-str1<<std::endl; }else{ std::cout<<"Notfound"<<std::endl; } return0; }

输出结果为:

Foundatposition:7
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门