C++中string函数用法总结

  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个字符


 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值