阅读量:2
在C++中,可以使用std::string::find_first_of()和std::string::find_last_of()函数来查找一个字符串中第一个和最后一个指定字符的位置
#include
#include
int main() {
std::string str = "Hello, I am a C++ assistant!";
char charsToFind[] = {'a', 'i', 'o', 'u', 'A', 'I', 'O', 'U'};
// 查找第一个字符的位置
size_t firstPos = str.find_first_of(charsToFind);
if (firstPos != std::string::npos) {
std::cout << "First occurrence of a character found at position: " << firstPos << std::endl;
} else {
std::cout << "No characters found." << std::endl;
}
// 查找最后一个字符的位置
size_t lastPos = str.find_last_of(charsToFind);
if (lastPos != std::string::npos) {
std::cout << "Last occurrence of a character found at position: " << lastPos << std::endl;
} else {
std::cout << "No characters found." << std::endl;
}
return 0;
}
在这个示例中,我们查找了字符串str中第一个和最后一个元音字母(a, i, o, u)的位置。find_first_of()返回第一个找到的字符的位置,而find_last_of()返回最后一个找到的字符的位置。如果没有找到任何字符,这两个函数都会返回std::string::npos。
以上就是关于“C++中使用strchr查找多个字符怎么办”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm