1)rfind
rfind全名reversefind
与find相反,
- size_type rfind( const basic_string &str, size_type index );
- size_type rfind( const char *str, size_type index );
- size_type rfind( const char *str, size_type index, size_type num );
- size_type rfind( char ch, size_type index );
rfind()函数:
- 返回最后一个与str中的某个字符匹配的字符,从index开始查找。如果没找到就返回string::npos
- 返回最后一个与str中的某个字符匹配的字符,从index开始查找,最多查找num个字符。如果没找到就返回string::npos
- 返回最后一个与ch匹配的字符,从index开始查找。如果没找到就返回string::npos
这里要注意与find不同的地方,rfind是从左往右数index个位置,这里作为基准index,然后从这里开始,从右往左数到第一次出现目标的位置。
find是在基准index从左往右数
例子
- #include <cstring>
- #include <iostream>
- int main()
- {
- int loc;
- std::string s = "My cat's breath smells like cat food.";
- loc = s.rfind( "breath", 8 );
- std::cout << "The word breath is at index " << loc << std::endl;
- //-1
- loc = s.rfind( "breath", 9 );
- std::cout << "The word breath is at index " << loc << std::endl;
- //9
- loc = s.rfind( "breath", 20 );
- std::cout << "The word breath is at index " << loc << std::endl;
- //9
- std::string ss = "Hi Bill, I'm ill, so please pay the bill";
- loc = ss.rfind("ill");
- std::cout << "The word breath is at index " << loc << std::endl;
- //37
- loc = ss.rfind("ill",20);
- std::cout << "The word breath is at index " << loc << std::endl;
- //13
- }
-
标准库的string类提供了3个成员函数来从一个string得到c类型的字符数组:c_str()、data()、copy(p,n)。
2. c_str():生成一个const char*指针,指向以空字符终止的数组。
注:
①这个数组的数据是临时的,当有一个改变这些数据的成员函数被调用后,其中的数据就会失效。因此要么现用先转换,要么把它的数据复制到用户自己可以管理的内存中。注意。看下例:
const
char
* c;
string s=
"1234"
;
c = s.c_str();
cout<<c<<endl;
//输出:1234
s=
"abcd"
;
cout<<c<<endl;
//输出:abcd
上面如果继续用c指针的话,导致的错误将是不可想象的。就如:1234变为abcd
其实上面的c = s.c_str(); 不是一个好习惯。既然c指针指向的内容容易失效,我们就应该按照上面的方法,那怎么把数据复制出来呢?这就要用到strcpy等函数(推荐)。
//const char* c; //①
//char* c; //②
//char c[20];
char
* c=
new
char
[20];
string s=
"1234"
;
//c = s.c_str();
strcpy
(c,s.c_str());
cout<<c<<endl;
//输出:1234
s=
"abcd"
;
cout<<c<<endl;
//输出:1234
注意:不能再像上面一样①所示了,const还怎么向里面写入值啊;也不能②所示,使用了未初始化的局部变量“c”,运行会出错的 。
② c_str()返回一个客户程序可读不可改的指向字符数组的指针,不需要手动释放或删除这个指针。
3. data():与c_str()类似,但是返回的数组不以空字符终止。