温馨提示×

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

c++
小亿
130
2023-11-30 02:14:28
栏目: 编程语言

在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;
}

0