1、const char *data();
data()函数返回指向自己的第一个字符的指针.
由于data()函数返回的是const char*,所以不能直接通过指针修改返回的字符串的值,如果要修改,必须把类型转化为char*.
2、const char *c_str();
c_str()函数返回一个指向正规C字符串的指针, 内容与本字符串相同.
作用类似于data(),返回的也是指向常量字符串的指针。
3、size_type copy( char *str, size_type num, size_type index );
copy()函数拷贝自己的num个字符到str中(从索引index开始)。返回值是拷贝的字符数。
非常有用的函数,要注意的是参数str一般为数组的名称,不能使用指针类型参数,因为需要预分配空间的。
4、int compare( const basic_string &str );
int compare( const char *str );
int compare( size_type index, size_type length, const basic_string &str );
int compare( size_type index, size_type length, const basic_string &str, size_type index2,
size_type length2 );
int compare( size_type index, size_type length, const char *str, size_type length2 );
compare()函数以多种方式比较本字符串和str,返回:
返回值 | 情况 |
---|---|
小于零 | this < str |
零 | this == str |
大于零 | this > str |
不同的函数:
- 比较自己和str,
- 比较自己的子串和str,子串以index索引开始,长度为length
- 比较自己的子串和str的子串,其中index2和length2引用str,index和length引用自己
- 比较自己的子串和str的子串,其中str的子串以索引0开始,长度为length2,自己的子串以index开始,长度为length
5、
查找(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
6、
substr
语法:
basic_string substr( size_type index, size_type num = npos ); |
substr()返回本字符串的一个子串,从index开始,长num个字符。如果没有指定,将是默认值 string::npos。这样,substr()函数将简单的返回从index开始的剩余的字符串。
7、
find_first_of
语法:
size_type find_first_of( const basic_string &str, size_type index = 0 ); size_type find_first_of( const char *str, size_type index = 0 ); size_type find_first_of( const char *str, size_type index, size_type num ); size_type find_first_of( char ch, size_type index = 0 ); |
find_first_of()函数:
- 查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,如果没找到就返回string::npos
- 查找在字符串中第一个与str中的某个字符匹配的字符,返回它的位置。搜索从index开始,最多搜索num个字符。如果没找到就返回string::npos,
- 查找在字符串中第一个与ch匹配的字符,返回它的位置。搜索从index开始。