C++中cstring查找字符串的方法是什么

   2025-02-13 3180
核心提示:在C++中,可以使用以下方法来查找字符串:使用std::string的find()函数:std::string类提供了一个find()函数,用于查找子字符串

在C++中,可以使用以下方法来查找字符串:

使用std::stringfind()函数:std::string类提供了一个find()函数,用于查找子字符串在主字符串中的位置。该函数返回子字符串首次出现的位置索引,如果找不到则返回std::string::npos。示例代码如下:
#include <iostream>#include <string>int main() {    std::string mainStr = "Hello, World!";    std::string subStr = "World";        size_t foundPos = mainStr.find(subStr);        if (foundPos != std::string::npos) {        std::cout << "Substring found at position " << foundPos << std::endl;    } else {        std::cout << "Substring not found" << std::endl;    }        return 0;}
使用C风格字符串的strstr()函数:cstring库中的strstr()函数用于在一个字符串中查找另一个字符串的第一次出现的位置。该函数返回一个指针,指向子字符串在主字符串中的位置,如果找不到则返回NULL。示例代码如下:
#include <iostream>#include <cstring>int main() {    const char* mainStr = "Hello, World!";    const char* subStr = "World";        char* foundPos = std::strstr(mainStr, subStr);        if (foundPos != nullptr) {        std::cout << "Substring found at position " << (foundPos - mainStr) << std::endl;    } else {        std::cout << "Substring not found" << std::endl;    }        return 0;}

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言