find_first_of查不到字符时返回std::string::npos,即无符号极大值(如18446744073709551615),不可与-1直接比较,须用== std::string::npos判断。
find_first_of 查不到字符时返回什么
find_first_of 找不到匹配字符时,返回 std::string::npos —— 这是个无符号整型常量,值为 static_cast(-1)。它不是 -1,而是极大值(比如 18446744073709551615)。直接跟 -1 比较会隐式转换出错,必须用 == std::string::npos 判断。
常见错误写法:if (pos == -1) 或 if (pos —— 因为 size_t 是无符号类型,pos 永远为假,编译器可能报警告。
find_first_of 和 find_first_not_of 的区别
find_first_of 在字符串中找「任意一个」出现在给定字符集合里的字符;而 find_first_not_of 找的是「第一个不在集合里」的字符。
- 对字符串
"abc123"调用s.find_first_of("0123456789")→ 返回位置 3(’1’) - 同样字符串调用
s.find_first_not_of("0123456789")→ 返回位置 0(’a’) - 如果字符串全是数字,比如
"123",find_first_not_of("0123456789")就返回npos
传入 C 风格字符串或 string 对象都行,但注意空字符处理
find_first_of 有多个重载:支持 const char*、std::string、甚至带长度的 const char*, size_t。但传 const char* 时,遇到首个 '\0' 就停止解析 —— 这是 C 字符串规则,不是函数 bug。
立即学习“C++免费学习笔记(深入)”;