- 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种 |
- string类的输入
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 stuff;
cin>>stuff; // read a word;
getline(cin,stuff); // read a line,discard \n
- string版本的getline()将自动调整目标string对象的大小,使之刚好能够存储输入的字符。
- 使用字符串
- 可以比较字符串,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():在字符串中查找最后一个不包含在参数中的字符。
- 前面提到的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;