方式一:使用find()函数进行查询
方式二:使用string容器自带的 find()函数进行操作
两个函数的区别是返回的值是不同的,find()函数会返回迭代器的对应位置,而string容器自带的find()函数返回的是下标值,如果未找到,则返回的是 -1。
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;
// 使用find()函数
void FindFunc()
{
/*
find()函数会在输入容器的范围内对key值进行查找,
如果找到,会返回容器对应的迭代器,
未找到,会返回迭代器的尾端位置
*/
string str;
cin >> str;
auto iter = find(str.begin(), str.end(), 'i');
if (iter != std::end(str))
cout << "find it " << *iter << endl;
else
cout << "not find" << endl;
return;
}
// 使用string中自带的find()函数
void StringFindFunc()
{
/*
string容器中自带的find()函数会返回所在元素的下标值,
如果未找到,则返回 -1
此函数对输入的字符串进行逆序排列 和 去重。
*/
string str;
cin >> str;
int len = str.length();
string newstr;
for (int i = len - 1; i >= 0; --i)
{
size_t pos = newstr.find(str[i]);
if (pos == -1)
newstr += str[i];
else
cout << "find it! pos = " << pos << " and value = " << str[pos] << endl;
}
cout << newstr << endl;
return;
}
int main()
{
FindFunc();
StringFindFunc();
return EXIT_SUCCESS;
}