C++ 中查找字符串是否包含特定字符
在 C++ 中,可以使用 STL 中的 find() 函数来查找字符串中是否含有特定字符。
示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = 'Hello World!';
char c = 'o';
if (str.find(c) != std::string::npos) {
std::cout << 'The string contains the character ' << c << std::endl;
} else {
std::cout << 'The string does not contain the character ' << c << std::endl;
}
return 0;
}
输出结果:
The string contains the character o
说明:
find()函数返回字符在字符串中首次出现的位置。- 如果字符不存在,则返回
std::string::npos。
其他方法:
除了 find() 函数,您还可以使用以下方法来查找字符串中是否包含特定字符:
std::string::find_first_of()函数:查找字符串中第一个出现的任何指定字符。std::string::find_last_of()函数:查找字符串中最后一个出现的任何指定字符。- 循环遍历字符串,检查每个字符是否与目标字符匹配。
选择最适合您的方法取决于您的具体需求。
原文地址: https://www.cveoy.top/t/topic/mC2Y 著作权归作者所有。请勿转载和采集!