string的find()与npos
在 C++ 中,std::string::find()
是一个用于在字符串中查找子字符串或字符的成员函数。查找成功时返回匹配的索引位置,查找失败时返回 std::string::npos
,表示未找到。
std::string::find()
函数原型
std::size_t find(const std::string& str, std::size_t pos = 0) const noexcept;
std::size_t find(const char* s, std::size_t pos = 0) const;
std::size_t find(char c, std::size_t pos = 0) const noexcept;
参数说明
str
/s
:要查找的子字符串或字符。pos
(可选):从哪个位置开始查找,默认为0
,即从字符串的开始位置查找。- 返回值:查找成功时返回第一个匹配字符的索引,查找失败时返回
std::string::npos
。
std::string::npos
std::string::npos
是一个常量,表示查找操作失败或子字符串不存在时的返回值。具体定义为 std::string::npos = -1
,它实际上是一个 std::size_t
类型的最大值。
示例
以下是一些简单的示例,演示如何使用 std::string::find()
和 std::string::npos
:
查找子字符串
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 查找子字符串 "World"
std::size_t found = str.find("World");
if (found != std::string::npos) {
std::cout << "Found 'World' at index: " << found << std::endl; // 输出: Found 'World' at index: 7
} else {
std::cout << "'World' not found." << std::endl;
}
// 查找不存在的子字符串 "Earth"
found = str.find("Earth");
if (found == std::string::npos) {
std::cout << "'Earth' not found." << std::endl; // 输出: 'Earth' not found.
}
return 0;
}
查找字符
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 查找字符 'o'
std::size_t found = str.find('o');
if (found != std::string::npos) {
std::cout << "Found 'o' at index: " << found << std::endl; // 输出: Found 'o' at index: 4
}
return 0;
}
从指定位置开始查找
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, World!";
// 从索引 5 开始查找字符 'o'
std::size_t found = str.find('o', 5);
if (found != std::string::npos) {
std::cout << "Found 'o' at index: " << found << std::endl; // 输出: Found 'o' at index: 8
}
return 0;
}
总结
std::string::find()
:用于查找字符串或字符。返回子字符串第一次出现的索引,或者返回std::string::npos
表示未找到。std::string::npos
:表示查找操作失败时的返回值(通常为最大值-1
表示无效位置)。