C++ string类的find()函数怎么用

假设我定义了一个string类如下string str("asdfggef");应该怎么调用find的函数,是不是这样,str.find("asdf").如果说要find的字串不在str里面,该函数会返回什么??str.find("asdf"); 的返回值是什么.str.find("...."); 的返回值又是什么???

查找(find)
语法:
size_type find( const basic_string &str, size_type index );
size_type find( const char *str, size_type index );
size_type find( const char *str, size_type index, size_type length );
size_type find( char ch, size_type index );

find()函数:

返回str在字符串中第一次出现的位置(从index开始查找)。如果没找到则返回string::npos,
返回str在字符串中第一次出现的位置(从index开始查找,长度为length)。如果没找到就返回string::npos,
返回字符ch在字符串中第一次出现的位置(从index开始查找)。如果没找到就返回string::npos
例如,

string str1( "Alpha Beta Gamma Delta" );
unsigned int loc = str1.find( "Omega", 0 );
if( loc != string::npos )
cout << "Found Omega at " << loc << endl;
else
cout << "Didn't find Omega" << endl;
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-02-13
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str="01234567890000";
int a;
a=str.find("0");
cout<<a<<endl;//返回0
a=str.find("123");
cout<<a<<endl;//返回1
a=str.find("456");
cout<<a<<endl;//返回4
system("Pause");
return 0;
}

查到第一个就返回,不管以后有几个,字符串就返回第一个字符的位置,从0开始数,运行下会更清楚
第2个回答  2012-02-13
返回的是要查找串在目标串中的索引位置,从0开始计数,找不到返回-1
第3个回答  2015-09-30
第4个回答  2015-11-03
string类的查找函数:
int find(char c, int pos = 0) const;//从pos开始查找字符c在当前字符串的位置
int find(const char *s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
int find(const char *s, int pos, int n) const;//从pos开始查找字符串s中前n个字符在当前串中的位置
int find(const string &s, int pos = 0) const;//从pos开始查找字符串s在当前串中的位置
//查找成功时返回所在位置,失败返回string::npos的值
int rfind(char c, int pos = npos) const;//从pos开始从后向前查找字符c在当前串中的位置
int rfind(const char *s, int pos = npos) const;
int rfind(const char *s, int pos, int n = npos) const;
int rfind(const string &s,int pos = npos) const;
//从pos开始从后向前查找字符串s中前n个字符组成的字符串在当前串中的位置,成功返回所在位置,失败时返回string::npos的值
int find_first_of(char c, int pos = 0) const;//从pos开始查找字符c第一次出现的位置
int find_first_of(const char *s, int pos = 0) const;
int find_first_of(const char *s, int pos, int n) const;
int find_first_of(const string &s,int pos = 0) const;
//从pos开始查找当前串中第一个在s的前n个字符组成的数组里的字符的位置。查找失败返回string::npos
int find_first_not_of(char c, int pos = 0) const;
int find_first_not_of(const char *s, int pos = 0) const;
int find_first_not_of(const char *s, int pos,int n) const;
int find_first_not_of(const string &s,int pos = 0) const;
//从当前串中查找第一个不在串s中的字符出现的位置,失败返回string::npos
int find_last_of(char c, int pos = npos) const;
int find_last_of(const char *s, int pos = npos) const;
int find_last_of(const char *s, int pos, int n = npos) const;
int find_last_of(const string &s,int pos = npos) const;
int find_last_not_of(char c, int pos = npos) const;
int find_last_not_of(const char *s, int pos = npos) const;
int find_last_not_of(const char *s, int pos, int n) const;
int find_last_not_of(const string &s,int pos = npos) const;
//find_last_of和find_last_not_of与find_first_of和find_first_not_of相似,只不过是从后向前查找