c++

如何利用str.find进行C++字符串分析

小樊
98
2024-08-08 23:19:39
栏目: 编程语言

在C++中,可以使用std::string类的find成员函数来进行字符串分析。find函数接受一个要搜索的子字符串作为参数,并返回子字符串在原字符串中第一次出现的位置。如果找到了子字符串,则返回子字符串在原字符串中的位置索引;如果未找到,则返回std::string::npos。以下是一个简单的示例:

#include <iostream>
#include <string>

int main() {
    std::string text = "Hello, World! This is a test string.";
    std::string subStr = "World";

    size_t found = text.find(subStr);
    if (found != std::string::npos) {
        std::cout << "Sub string found at position: " << found << std::endl;
    } else {
        std::cout << "Sub string not found." << std::endl;
    }

    return 0;
}

在上面的示例中,我们定义了一个字符串text和一个子字符串subStr,然后使用find函数查找子字符串在原字符串中的位置。如果找到了子字符串,则输出子字符串在原字符串中的位置索引,否则输出未找到的提示。

0
看了该问题的人还看了