c++ - 在字符串中查找字母返回不同的数字
问题描述
为什么phrase.find("333", 0)
return4
和phrase.find("333", 2)
return4
一样?
我的程序工作正常吗?不应该在第二个字符之后搜索 333 吗?
int main() {
string phrase = "text333 fdsfwsawa";
cout << phrase.find("333", 2) << endl;
return 0;
}
解决方案
size_type find(const basic_string& str, size_type pos = 0) const;
上面我们有一个 Find() 的声明。
返回值: size_type :找到的子字符串的第一个字符的位置,如果没有找到这样的子字符串,则返回 npos。
参数:str:你的输入字符串
pos:在字符串中要从哪个位置开始搜索,默认为 0
#include <string>
#include <iostream>
void print(std::string::size_type n, std::string const &s)
{
if (n == std::string::npos) {
std::cout << "not found\n";
} else {
std::cout << "found: " << s.substr(n) << '\n';
}
}
int main()
{
std::string::size_type n;
std::string const s = "This is a string";
// search from beginning of string
std::cout<< s.find("is");
// search from position 5
std::cout<< s.find("is", 5);
// find a single character
std::cout<< s.find('a');
}
输出:
2
5
8
在您的问题phrase.find("333", 0)
中,它将从位置零开始搜索,并在位置 4 找到“333”。
推荐阅读
- r - Problems with labs(caption =... in ggplot as well as in ggsave - error "Error in titleGrob"
- azure-durable-functions - Durable Functions - Is Round robin activity scheduling possible?
- javascript - 计算对象数组中属性的平均值
- javascript - 获取偶数个数组的中间两项
- javascript - React - hide component when an element in Navigation menu is clicked
- xamarin - Xamarin ios 14 permissions not showing in device settings
- google-analytics - User identification in Google Analytics
- c++ - 在 CMAKE 项目 Visual Studio 中添加自定义标头
- node.js - Nodejs和使用未存储在Firefox中的会话数据表达,chrome浏览器工作正常
- sql - Laravel 8 - 模型上的“刷新()”不执行匿名全局范围