在C++中,可以使用以下方法来查找字符串:
std::string
的find()
函数:std::string
类提供了一个find()
函数,用于查找子字符串在主字符串中的位置。该函数返回子字符串首次出现的位置索引,如果找不到则返回std::string::npos
。示例代码如下:#include <iostream>
#include <string>
int main() {
std::string mainStr = "Hello, World!";
std::string subStr = "World";
size_t foundPos = mainStr.find(subStr);
if (foundPos != std::string::npos) {
std::cout << "Substring found at position " << foundPos << std::endl;
} else {
std::cout << "Substring not found" << std::endl;
}
return 0;
}
strstr()
函数:cstring
库中的strstr()
函数用于在一个字符串中查找另一个字符串的第一次出现的位置。该函数返回一个指针,指向子字符串在主字符串中的位置,如果找不到则返回NULL
。示例代码如下:#include <iostream>
#include <cstring>
int main() {
const char* mainStr = "Hello, World!";
const char* subStr = "World";
char* foundPos = std::strstr(mainStr, subStr);
if (foundPos != nullptr) {
std::cout << "Substring found at position " << (foundPos - mainStr) << std::endl;
} else {
std::cout << "Substring not found" << std::endl;
}
return 0;
}