C++中的std::string类提供了几种查找功能,包括find(), rfind(), find_first_of(), find_last_of()等。下面是这些函数的简单介绍和示例:
size_t find(const std::string& str, size_t pos = 0) const noexcept;
在当前字符串中从位置pos开始查找子字符串str第一次出现的位置。如果找不到则返回std::string::npos。
#include<iostream>
#include<string>
int main() {
std::string s("hello world");
std::string sub("world");
size_t pos = s.find(sub);
if (pos != std::string::npos) {
std::cout << "Found at position: "<< pos<< std::endl;
} else {
std::cout << "Not found"<< std::endl;
}
return 0;
}
size_t rfind(const std::string& str, size_t pos = npos) const noexcept;
在当前字符串中从位置pos开始查找子字符串str最后一次出现的位置。如果找不到则返回std::string::npos。
#include<iostream>
#include<string>
int main() {
std::string s("hello world world");
std::string sub("world");
size_t pos = s.rfind(sub);
if (pos != std::string::npos) {
std::cout << "Found at position: "<< pos<< std::endl;
} else {
std::cout << "Not found"<< std::endl;
}
return 0;
}
size_t find_first_of(const std::string& str, size_t pos = 0) const noexcept;
在当前字符串中从位置pos开始查找str中任意字符第一次出现的位置。如果找不到则返回std::string::npos。
#include<iostream>
#include<string>
int main() {
std::string s("hello world");
std::string chars("wro");
size_t pos = s.find_first_of(chars);
if (pos != std::string::npos) {
std::cout << "Found at position: "<< pos<< std::endl;
} else {
std::cout << "Not found"<< std::endl;
}
return 0;
}
size_t find_last_of(const std::string& str, size_t pos = npos) const noexcept;
在当前字符串中从位置pos开始查找str中任意字符最后一次出现的位置。如果找不到则返回std::string::npos。
#include<iostream>
#include<string>
int main() {
std::string s("hello world");
std::string chars("wro");
size_t pos = s.find_last_of(chars);
if (pos != std::string::npos) {
std::cout << "Found at position: "<< pos<< std::endl;
} else {
std::cout << "Not found"<< std::endl;
}
return 0;
}
这些函数可以根据需要进行组合使用,以实现更复杂的查找功能。注意,当使用std::string::npos作为参数时,表示从字符串的末尾开始查找。