string类的一些成员函数

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开始。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值