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

c++
1100
2023/12/27 2:14:28
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

  1. 使用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;
}
  1. 使用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;
}

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 如何优化C++ map拷贝的效率