初学者可能会对string类的对象初始化不是很清楚,看了这个就不怕啦....~~~
可以对比着c中的字符串对比哦
string类是由头文件string支持的,其中包含了大量的方法,其中包括了若干的构造函数,用于将字符串赋值给变量,合并字符串,比较字符串和访问各个元素的重载运算符以及用于在字符串中查找字符和子字符串的工具
常用构造字符串:
string(const char * s) | 将string对象初始化为s指向的字符串 |
string(int n, char c) | 创建一个包含n个元素的string对象,其中每个字符串都被初始化为字符c |
string(const string &str) | 将一个string对象初始化为string对象str(赋值构造函数) |
string() | 创建一个默认的string对象, 长度为0(默认构造函数) |
string(const char *s , int n) | 将string 对象初始化为s指向的字符串的前n、个字符,即使超过了字符串的尾部 |
template<class Iter> string(Iter begin , Iter end) | 将string对象初始化为区间[begin,end)内的字符,其中begin和end 的行为就像指针,用于指定位置,范围包括begin在内, 但不包括end |
string(const string &str, string size_type pos = 0, int n = npos) | 将一个string对象初始化为对象str中从位置pos开始到结尾的字符, 或从位置pos开始的n个字符 |
程序清单:
string one(“hello world”);
cout << one <<endl;
输出: hello world
string two(5, ‘#’);
cout << two << endl;
输出: #####
string three(two);
cout << three << endl;
输出: #####
string four;
four = one + two;
cout << four << endl;
输出: hello world#####
four = four + “xiaobaitu”
cout << four << endl;
输出: hello world#####xiaobaitu
string 类中对+、+=操作符进行了重载, string对象和string对象或字符串常量可以进行+、+=操作
three[0] = p;
cout << three << endl;
输出: p####
string类中对[]操作符进行了重载,可以通过[]访问字符串中的各个字符
char a[] = “allof us with you”;
string five(a,10);
cout <<five << endl;
输出: all of us w
string six(a+2,a+6);
cout <<six << endl;
输出:l of
stringseven(five, 2, 8);
cout <<seven << endl;
输出: l of u
string 类中对大部分的操作符都进行了重载,包括,+、+=、=、<< 、>>、[ ]等基本操作符
有什么错误或者有哪些需要添加的, 请各位帮忙指出来,thanks...