构建一个字符串对象的方法很多,string 类中有多个重载的构造函数用于初始化一个字符串类对象。
构建函数 | 作用 |
string str | 初始化一个空串str |
string s("123456789") | 利用字符串常量初始化对象s |
sring str(s) | str是s的副本 |
string str(s,2) | 使用是【2-end]初始化 |
string str(s,2,5) | str="34567" |
string str(5,'c') | str="ccccc" |
string str(s.begin(),s.end()) | 迭代器初始化 |
迭代器读取字符串
#include<iostream>
using namespace std;
#include<string>
int main()
{
string line("123456789");
cout << string(line.begin(), line.end()) << endl;//正向迭代器
cout << string(line.rbegin(), line.rend()) << endl;//反向迭代器
//定义迭代器
string::iterator it;
for (it = line.begin(); it != line.end(); it++)
{
cout << *it;
}
cout << endl;
string::reverse_iterator it1;
for (it1 = line.rbegin(); it1 != line.rend(); it1++)
{
cout << *it1;
}
return 0;
}
字符串容量:
- size 和 length 返回字符串的长度;
- empty 判断字符串是否为空
- clear 清空字符串
- max_size 返回字符串的最大长度
- resize 修改字符串的长度,不重新分配空间
- capacity 返回不重新分配内存的最大字符数
- reserve 增加字符串空间
#include<iostream>
using namespace std;
#include<string>
int main()
{
string str("123456789");
str.reserve(100);//重新分配空间保留字符数
cout << str.capacity() << endl;
int size = str.size();
int length = str.length();
unsigned long maxsize = str.max_size();
cout << "capacity = " << str.capacity() << endl;
cout << "size = " << str.size() << endl;
cout << "length = " << str.length() << endl;
cout << "maxsize = " << str.max_size() << endl;
if (!str.empty())
{
cout << "str = " << str << endl;
}
return 0;
}
修改字符串:
- assign 给字符串赋值
- operator+= 追加字符串
- append 追加字符串
- push_back 追加单个字符
- insert 插入字符串
- erase 删除部分字符串
- replace 替换部分字符串
- swap 两个字符串交换内容
-》assign()
#include<iostream>
using namespace std;
#include<string>
int main()
{
string str("123456789");
string str2;
str2.assign(str);//将str的值拷贝到str2中
cout << "str2 = " << str2 << endl;
str2.assign(str, 6, 2);
cout << "str2 = " << str2 << endl;
str2.assign(5, 'x');
cout << "str2 = " << str2 << endl;
return 0;
}
-》append
#include<iostream>
using namespace std;
#include<string>
int main()
{
string str("123456789");
string str2 = "qwert";
str.append(str2);
cout << "str = " << str << endl;
str.append(str2, 2, 3);
cout << "str = " << str << endl;
str.append("zxc", 0, 2);
cout << "str = " << str << endl;
str.push_back('P');
cout << "str = " << str << endl;
str += "vbn";
cout << "str = " << str << endl;
return 0;
}
->insert 和erase
#include<iostream>
using namespace std;
#include<string>
int main()
{
string str("0123456789");
string str2 = "abce";
cout << "str = " << str << endl;
str.erase(5);
cout << "str = " << str << endl;
str.erase(2, 3);
cout << "str = " << str << endl;
str2.insert(2, str);
cout << "str2 =" << str2 << endl;
str2.insert(2, "西湖大学");
cout << "str2 =" << str2 << endl;
return 0;
}