在C++ string容器的find函数和rfind函数得到结果是一样的
在练习string容器相关知识时报错。
#include<iostream>
#include<string>
using namespace std;
//字符串拼接
void joint()
{
string str1 = "hello";
string str2 = "world";
cout << str1 + str2 << endl;
str1.append(str2);
cout << str1 << endl;
str2.assign("hhhh");
cout << str2 << endl;
}
//字符串查找
void find()
{
string str1 = "hello world";
int pos = str1.find("ld");
cout << pos << endl;
int pos1 = str1.rfind("ld");
cout << pos1 << endl;
}
//字符串比较
//插入和删除
//子串获取
int main()
{
find();
system("pause");
}
find函数从左到右开始寻找,rfind函数从右到左开始寻找。
pos = 9;
pos1 = 0;
因为你寻找的是同一个字符串,而且这个字符串只出现一次。所以得到的都是这个字符串在原字符串中的起始位置。
如果想要达到你要的结果,可以这么改
int pos1 = str1.size() - str1.rfind("ld") - strlen("ld");
原来的字符串只含有一个ld啊,所以都是那个ld的位置