C++(find())

发布时间 2023-12-14 15:01:28作者: 做梦当财神

在 C++ 中,find() 函数是字符串类(std::string)的成员函数,用于在字符串中查找特定的子字符串或字符。这函数有两个主要版本:一个是用于查找字符的版本,另一个用于查找子字符串的版本。

查找字符版本:

size_t find(const char& ch, size_t pos = 0) const;
  • 参数
    • ch:要查找的字符。
    • pos:可选参数,指定开始查找的位置,默认为 0。
  • 返回值
    • 如果找到字符,则返回找到的第一个字符的位置索引;如果未找到,返回 std::string::npos

示例:

std::string str = "Hello, World!";
size_t position = str.find('W');
if (position != std::string::npos) {
    std::cout << "Found at position: " << position << std::endl;
} else {
    std::cout << "Not found." << std::endl;
}

查找子字符串版本:

size_t find(const std::string& str, size_t pos = 0) const;
  • 参数
    • str:要查找的子字符串。
    • pos:可选参数,指定开始查找的位置,默认为 0。
  • 返回值
    • 如果找到子字符串,则返回找到的第一个字符的位置索引;如果未找到,返回 std::string::npos

示例:

std::string str = "Hello, World!";
size_t position = str.find("World");
if (position != std::string::npos) {
    std::cout << "Found at position: " << position << std::endl;
} else {
    std::cout << "Not found." << std::endl;
}

使用 find() 查找多个匹配:

可以使用循环结构和适当的处理,多次调用 find() 来查找多个匹配。

std::string str = "Hello, Hello, World!";
size_t pos = 0;
while ((pos = str.find("Hello", pos)) != std::string::npos) {
    std::cout << "Found at position: " << pos << std::endl;
    pos += 5;  // Move past the found substring to avoid infinite loop
}

这样的循环可以找到字符串中所有匹配的子字符串的位置。