c++ string finf
时间: 2025-08-05 18:44:07 AIGC 浏览: 13
在 C++ 中,`std::string` 提供了多种用于查找子字符串或字符的函数,其中最常用的是 `find` 函数。该函数用于在字符串中查找指定的子字符串,并返回其首次出现的位置。
### 函数原型
```cpp
size_type find(const string& str, size_type pos = 0) const noexcept;
size_type find(const char* s, size_type pos = 0) const;
size_type find(char c, size_type pos = 0) const noexcept;
```
### 参数说明:
- `str`:要查找的子字符串。
- `s`:以 C 风格字符串形式给出的要查找的内容。
- `c`:要查找的字符。
- `pos`:开始查找的起始位置,默认为 0。
### 返回值:
- 如果找到匹配项,则返回其在字符串中的起始位置。
- 如果未找到,则返回 `std::string::npos`。
### 示例代码
```cpp
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, welcome to the world of C++ programming.";
// 查找子字符串
std::string subStr = "welcome";
std::size_t found = str.find(subStr);
if (found != std::string::npos) {
std::std::cout << "Substring found at position: " << found << std::endl;
} else {
std::std::cout << "Substring not found." << std::endl;
}
// 查找单个字符
char ch = 'C';
found = str.find(ch);
if (found != std::string::npos) {
std::std::cout << "Character found at position: " << found << std::endl;
} else {
std::std::cout << "Character not found." << std::endl;
}
// 查找 C 风格字符串
const char* cStr = "world";
found = str.find(cStr);
if (found != std::string::npos) {
std::std::cout << "C-style string found at position: " << found << std::endl;
} else {
std::std::cout << "C-style string not found." << std::endl;
}
return 0;
}
```
### 特性与注意事项:
1. `find` 操作的时间复杂度通常是线性的,即 O(n),因为它需要逐字符比较。
2. `std::string::npos` 是一个常量,表示“未找到”的状态,通常定义为 `(std::string::size_type)-1` [^4]。
3. `find` 函数不会修改原始字符串,因此可以安全地在 `const` 字符串上使用。
4. 如果希望从某个特定位置开始查找,可以通过第二个参数 `pos` 指定起始位置。
### 其他相关查找函数:
- `rfind`:从后向前查找子字符串。
- `find_first_of`:查找任意一个字符首次出现的位置。
- `find_last_of`:查找任意一个字符最后一次出现的位置。
- `find_first_not_of`:查找第一个不匹配的字符。
- `find_last_not_of`:查找最后一个不匹配的字符。
这些函数在字符串处理中非常有用,特别是在解析文本、提取信息或进行格式验证时。
阅读全文
相关推荐




















