t;string>#include <iostream>
using namespace std;
void main()
{
string s1("hehe",2,3);
string s2(s1);
cout<<s2<<endl;
cin.get();
}
6)
#include <string>
#include <iostream>
using namespace std;
void main()
{
char chs[] = "hehe";
string s(chs,3); //将chs前3个字符作为初值构造
cout<<s<<endl;
cin.get();
}
7)
#include <string>
#include <iostream>
using namespace std;
void main()
{
string s(10,'k'); //分配10个字符,初值都是'k'
cout<<s<<endl;
cin.get();
}
//以上是string类实例的构造手段,都很简单.
9)
//赋新值
#include <string>
#include <iostream>
using namespace std;
void main()
{
string s(10,'k'); //分配10个字符,初值都是'k'
cout<<s<<endl;
s = "hehehehe";
cout<<s<<endl;
s.assign("kdje");
cout<<s<<endl;
s.assign("fkdhfkdfd",5); //重新分配指定字符串的前5的元素内容
cout<<s<<endl;
cin.get();
}
10)
//swap方法交换
#include <string>
#include <iostream>
using namespace std;
void main()
{
string s1 = "hehe";
string s2 = "gagaga";
cout<<"s1 : "<<s1<<endl;
cout<<"s2 : "<<s2<<endl;
s1.swap(s2);
cout<<"s1 : "<<s1<<endl;
cout<<"s2 : "<<s2<<endl;
cin.get();
}
11)
//+=,append(),push_back()在尾部添加字符
#include <string>
#include <iostream>
using namespace std;
void main()
{
string s = "hehe";
s += "gaga";
cout<<s<<endl;
s.append("嘿嘿"); //append()方法可以添加字符串
cout<<s<<endl;
s.push_back('k'); //push_back()方法只能添加一个字符...
cout<<s<<endl;
cin.get();
}
12)
//insert() 插入字符.其实,insert运用好,与其他的插入操作是一样的.
#include <string>
#include <iostream>
using namespace std;
void main()
{
string s = "hehe";
s.insert(0,"头部"); //在头部插入
s.insert(s.size(),"尾部"); //在尾部插入
s.insert(s.size()/2,"中间");//在中间插入
cout<<s<<endl;
cin.get();
}
13)
#include <string>
#include <iostream>
using namespace std;
void main()
{
string s = "abcdefg";
s.erase(0,1); //从索引0到索引1,即删除掉了'a'
cout<<s<<endl;
//其实,还可以使用replace方法来执行删除操作
s.replace(2,3,"");//即将指定范围内的字符替换成"",即变相删除了
cout