一 string类
1、构造字符串
string共有9个构造函数(包括C++11新增),同时,它也是模板具体化basic_string<char>的一个typedef,并省略了与内存管理相关的参数。
string(const char *s) | 将string对象初始化为s指向的NBTS |
string(size_type n,char c) | 创建一个包含n个元素的string类对象,其中每个元素被初始化为字符c |
string(const string&str) | 将一个string对象初始化为string对象str(复制构造函数) |
string() | 创建一个默认的string对象,长度为0 |
string(const char *s, size_type n) | 将string对象初始化为s指向的NBTS的前n个字符,即使超过了NBTS的结尾。 |
template<class Iter>string(Iter Begin, Iter end) | 将string初始化为区间[begin, end)内的字符——即使超过了NBTS的结尾。 |
string(const string & str, string size_type pos = 0, size_type n = npos) |
将一个string对象初始化为str中从pos开始到结尾的n个字符或到结尾。 |
string(string&& str)noexcept | 将一个string对象初始化为string对象str,并可能修改str的值。 |
string(initialize_list<char>il) | 将一个string对象初始化为il中的字符 |
#include<iostream>
#include<string>
int main()
{
using namespace std;
string one("Lottery Winner!");
cout<<one<<endl;
string two(20, '$');
cout<<two<<endl;
string three(one);
cout<<three<<endl;
one+=" Oops!";
cout<<one<<endl;
two = "Sorry! That was ";
three[0] = 'P';
string four = two + three;//overloading
char alls[] = "All's well that ends well";
string five(alls, 20);
cout<< five<<endl;
string six(alls+6,alls +10);
cout<<six<<", ";
string seven(&five[6], &five[10]);
cout<<seven<<"...\n";
return 0;
}
2、字符串输入。
1、C-风格字符串
char info[100];
cin>>info;
cin.getline(info, 100); //会在语句末将换行符丢弃
cin.get(info, 100); //仍然会将换行符放在队列中
2、string对象
string stuff;
cin>>stuff;
getline(cin, stuff);
关于getline的重载:在两个getline中,均有一个可选参数的重载版本——它用来指定哪个字符用来确定边界