C++基础(6)——string类

  1. string类的构造字符串
构造函数描述
string(const char *s)将string对象初始化为s指向的NBTS(null-terminated string)
string(size_type n,char c)创建一个包含n个元素的string对象,其中每个元素都被初始化为字符c
string(const string & str)将一个string对象初始化为string对象str(复制构造函数)
string()创建一个默认的string对象,长度为0(默认构造函数)
[C++.Primer.Plus(第6版)中文版]P675还有5种
  1. string类的输入
  • 对于C-风格字符串,有三种方式:
char info[100];
cin>>info; //read a word
cin.getline(info,100); //read a line,discard \n
cin.get(info,100);  //read a line,leave \n in queue
  • 对于string对象,有两种方式:
string stuff;
cin>>stuff;   //  read a word;
getline(cin,stuff);  // read a line,discard \n
  • string版本的getline()将自动调整目标string对象的大小,使之刚好能够存储输入的字符。
  1. 使用字符串
  • 可以比较字符串,String类对全部6个关系运算符都进行了重载。
  • 重载的find()方法
方法原型描述
size_type find(const string &str, size_type pos = 0)const从字符串的pos位置开始,查找子字符串str。如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回string::opos
size_type find(const char * s, size_type pos = 0)const从字符串的pos位置开始,查找子字符串s。如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回string::opos
size_type find(const char * s, size_type pos = 0,size_type n)从字符串的pos位置开始,查找s的前n个字符组成的子字符串。如果找到,则返回该子字符串首次出现时其首字符的索引;否则,返回string::opos
size_type find(char ch, size_type pos = 0)const从字符串的pos位置开始,查找字符ch。如果找到,则返回该字符首次出现的位置;否则,返回string::opos
  • string库还提供了相关的方法,它们重载函数特征标都与find函数方法相同:
    • rfind():查找子字符串或字符最后一次出现的位置
    • find_first_of():在字符串中查找参数中任何一个字符首次出现的位置。
    • find_last_of():在字符串中查找参数中任何一个字符最后一次出现的位置。
    • find_first_not_of():在字符串中查找第一个不包含在参数中的字符。
    • find_last_not_of():在字符串中查找最后一个不包含在参数中的字符。
  1. 前面提到的string类看作是基于char类型的,事实上,string库实际上是基于一个模板类的:
template<class charT,class traits = char _traits<charT>,
               class Allocator = allocator<charT> >
basic_string{...};
//模板basic_string 有4个具体化,每个具体化都有一个typedef名称:
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
typedef basic_string<char16_t> u16string;
typedef basic_string<char32_t> u32string;
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值