string的构造函数
string() //无参构造,初始化为空串 string(const string& str) //用str拷贝构造 string(size_t n,char c) //用n个字符c初始化 string(const char* s,size_t n) //用字符串s的前n个字符初始化 string(const string& str,size_t pos,size_t len=npos) //将字符串str,从下标pos位置开始,选取长度为len个的字符,来初始化
代码语言:javascript
AI代码解释
string str1; //空串
string str2("hello world"); //用"hello world"拷贝构造str2
string str3(4, 'x'); //用4个字符'x'初始化
string str4(str2, 5, 6); //用str2中,从下标为5位置开始,长度为6的字符串初始化
string("hello world", 5); //用字符串"hello world" 前5个字符初始化

string(const string& str,size_t pos,size_t len=npos)
注:上面的缺省值npos,定义为:size_t npos=-1. npos为最大值,表示不传参数时,会用str中pos位置开始后的所有字符来初始化
二,string的大小和容量
size()和length():返回string对象的字符个数 capacity():string对象的容量,也就是可以存储字符的最大个数
代码语言:javascript
AI代码解释
string str("hello world");
cout << "size==" << str.size() << endl;
cout << "length==" << str.length() << endl;
cout << "capacity==" << str.capacity() << endl;

三,string的插入
insert
代码语言:javascript
AI代码解释
string str1("hello world");
str1.insert(5, "xxxxxx"); //在5位置之前插入字符串"xxxxxx"
cout << str1 << endl;
string str2("hello world");
str2.insert(5, 2, '%'); //在5位置之前插入2个"%"
cout << str2 << endl;
string str3("hello world");
string::iterator it1 = str3.begin();
str3.insert(it1, '#'); //在开始位置之前插入'#'
cout << str3 << endl;
string str4("hello world");
string::iterator it2 = str4.begin();
str4.insert(it2, 2, '#'); //在开始位置之前插入两个'#'
cout << str4 << endl;

push_back(尾插)
代码语言:javascript
AI代码解释
string s; //空串
s.push_back('a'); //尾插
s.push_back('c');
s.push_back('b'); //s中存放的字符串为"abc"
四,string的遍历
迭代器遍历或者下标遍历
代码语言:javascript
AI代码解释
string str1("hello world");
//下标遍历
for (int i = 0; i < str1.size(); i++)
{
cout << str1[i];
}
cout << endl;
//迭代器遍历
//正向迭代器
string::iterator it1 = str1.begin();
while (it1 != str1.end())
{
cout << *it1;
it1++;
}
cout << endl;
//反向迭代器
string::reverse_iterator it2 = str1.rbegin();
while (it2 != str1.rend())
{
cout << *it2;
it2++;
}
cout << endl;
//const正向迭代器
const string s("hello world");
string::const_iterator cit = s.begin();
while (cit != s.end())
{
cout << *cit;
cit++;
}
cout << endl;
//const反向迭代器
string::const_reverse_iterator crit = s.rbegin();
while (crit != s.rend())
{
cout << *crit;
crit++;
}
cout << endl;

五,string的删除
erase(iterator p); //删除p所指位置的字符 erase(iteraror first,iterator last) //迭代器区间删除,删除first到last区间的字符 erase(size_t pos,size_t len=npos) //删除pos位置开始的len个字符

1万+

被折叠的 条评论
为什么被折叠?



