温馨提示×

c++怎么判断字符串中是否包含某个字符

c++
小亿
446
2023-11-09 09:14:02
栏目: 编程语言

在C++中,你可以使用`std::string`类的成员函数`find()`来判断一个字符串中是否包含某个字符。`find()`函数返回该字符在字符串中第一次出现的位置,如果未找到,则返回一个特殊的值 `std::string::npos`。

以下是一个示例代码:

#include 
#include 
int main() {
    std::string str = "Hello, World!";
    char ch = 'o';
    
    size_t found = str.find(ch);
    
    if (found != std::string::npos) {
        std::cout << "Character '" << ch << "' found at position " << found << std::endl;
    } else {
        std::cout << "Character '" << ch << "' not found in the string" << std::endl;
    }
    
    return 0;
}

运行以上代码,输出将是:

Character 'o' found at position 4

如果你想要判断字符串中是否包含某个子字符串,可以使用`std::string`的另一个成员函数`find()`来完成。用法与上述示例类似,只需要将字符参数改为字符串参数即可。

0