c++判断字符串中是否包含某个字符
作者:野牛程序员:2023-07-15 14:00:55 C++阅读 4365
在 C++ 中,你可以使用 std::string
类提供的成员函数 find
或 find_first_of
来判断字符串是否包含某个字符。下面是两种常用的方法:
方法一:使用 find
函数
#include <iostream> #include <string> int main() { std::string str = "Hello, World!"; char ch = 'o'; if (str.find(ch) != std::string::npos) { std::cout << "字符串包含字符 '" << ch << "'" << std::endl; } else { std::cout << "字符串不包含字符 '" << ch << "'" << std::endl; } return 0; }
方法二:使用 find_first_of
函数
#include <iostream> #include <string> int main() { std::string str = "Hello, World!"; char ch = 'o'; if (str.find_first_of(ch) != std::string::npos) { std::cout << "字符串包含字符 '" << ch << "'" << std::endl; } else { std::cout << "字符串不包含字符 '" << ch << "'" << std::endl; } return 0; }
这两种方法都会返回一个位置索引,如果找到了该字符,则返回其在字符串中的位置索引;如果没有找到,则返回 std::string::npos
,即一个特殊的常量值。因此,可以通过判断返回值是否等于 std::string::npos
来确定字符串是否包含某个字符。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:c++怎么输出字符串
- 下一篇:html中如何引入外部js文件