阅读量:107
在C++中,可以使用以下方法来查找字符串:
- 使用
std::string的find()函数:std::string类提供了一个find()函数,用于查找子字符串在主字符串中的位置。该函数返回子字符串首次出现的位置索引,如果找不到则返回std::string::npos。示例代码如下:
#include
#include
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 class="hljs-keyword">else {
std::cout << "Substring not found" << std class="hljs-keyword">return 0;
}
- 使用C风格字符串的
strstr()函数:cstring库中的strstr()函数用于在一个字符串中查找另一个字符串的第一次出现的位置。该函数返回一个指针,指向子字符串在主字符串中的位置,如果找不到则返回NULL。示例代码如下:
#include
#include
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 class="hljs-keyword">else {
std::cout << "Substring not found" << std class="hljs-keyword">return 0;
}