📅  最后修改于: 2023-12-03 15:29:52.532000             🧑  作者: Mango
在 C++ 中,我们可以使用字符串函数来在字符串中查找另一个字符串。下面是一些常见的字符串函数:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
size_t found = str.find("World");
if (found != std::string::npos) {
std::cout << "Found at position: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
size_t found = str.rfind("l");
if (found != std::string::npos) {
std::cout << "Found at position: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
size_t found = str.find_first_of("ol");
if (found != std::string::npos) {
std::cout << "Found at position: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
size_t found = str.find_last_of("ol");
if (found != std::string::npos) {
std::cout << "Found at position: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
size_t found = str.find_first_not_of("Hello ");
if (found != std::string::npos) {
std::cout << "Found at position: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
#include <iostream>
#include <string>
int main() {
std::string str = "Hello World";
size_t found = str.find_last_not_of("World");
if (found != std::string::npos) {
std::cout << "Found at position: " << found << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
你也可以使用正则表达式来查找字符串,不过这涉及到了 C++ 的正则表达式库,这里就不详细介绍了。
在 C++ 中,我们可以使用各种字符串函数来查找字符串。这些函数非常方便且易于使用,可以大大简化我们的开发工作。如果您需要在字符串中查找字符串,请选择最适合您用例的函数并开始 coding 吧!