1.string的基本概念
string是一个类,封装了char*,管理这个字符串,是一个char*型的容器。
其中也包含了若干构造函数 ,我们结合实例讲解最常用的一些构造函数,这些构造函数可以在刷题或者做项目时为我们提供很大帮助
2.string的构造函数
#include<iostream>
#include<string>
using namespace std;
//string的基本概念,string是一个类,封装了char*,管理这个字符串,是一个char*型的容器
//string的构造函数
void stringout()
{
string s1;//默认构造
//初始化字符串str;
const char*str="hello world";
string s2(str);
cout<<"s2= "<<s2<<endl;
//使用一个string对象初始化另一个string对象
string s3(s2);
cout<<"s3= "<<s3<<endl;
//使用n个字符c初始化
string s4(10,'a');
cout<<"s4= "<<s4<<endl;
}
int main()
{
stringout();
}
运行结果
3.给string字符进行赋值
#include<iostream>
#include<string>
using namespace std;
//string的基本概念,string本质是一个类,封装了char*和很多的成员函数,管理这个字符串,是一个char*型的容器
//给string字符进行赋值
void stringout()
{
//1.普通赋值
string s1;
s1="hello world";
cout<<"s1= "<<s1<<endl;
//2.把一个字符串赋给当前的字符串
string s2;
s2=s1;
cout<<"s2= "<<s2<<endl;
//3.利用assign(const char*s)赋值 ,把字符串s赋给当前的字符串
string s3;
s3.assign("hello zhaoAlong");
cout<<"s3= "<<s3<<endl;
//4.利用assign(const char*s,int n)赋值 ,把字符串s的前n个字符赋给当前的字符串
string s4;
s4.assign("hello zhaoAlong",10) ;
cout<<"s4= "<<s4<<endl;
//5.利用assign(const string &s)赋值 ,把字符串s赋给当前的字符串
string s5;
s5.assign(s3);
cout<<"s5= "<<s5<<endl;
//6.利用assign(int n,char c)赋值 ,把n个字符c赋给当前的字符串
string s6;
s6.assign(10,'p');
cout<<"s6= "<<s6<<endl;
}
int main()
{
stringout();
}
运行结果
4.string字符串拼接
#include<iostream>
#include<string>
using namespace std;
//string字符串拼接,实现在字符串末尾拼接字符串
void stringout()
{
//1.追加一个字符串或一个字符
string s1="zhaoAlong";
s1+="-std";
cout<<"s1= "<<s1<<endl;
// 2.将一个字符串追加到当前字符串末尾
string s2="hello";
s2+=s1;
cout<<"s2= "<<s2<<endl;
//3.利用append函数追加一个字符串
string s3="lihua";
s3.append("+xiaoming");
cout<<"s3= "<<s3<<endl;
//4.利用append函数追加一个字符串的前n个字符
string s4="lihua";
s4.append("+xiaoming",5);
cout<<"s4= "<<s4<<endl;
//5.将一个string字符串追加到当前字符串末尾
string s5="lihua";
s5.append(s4);
cout<<"s5= "<<s5<<endl;
//6.利用append函数追加一个字符串中从n开始的m个字符
string s6="lihua";
s6.append("+xiaoming",2,5);
cout<<"s6= "<<s6<<endl;
}
int main()
{
stringout();
}
运行结果
5.string的插入和删除
#include<iostream>
#include<string>
using namespace std;
//string的插入和删除
void stringout()
{
//1.插入
//利用insert在当前字符串第n个元素后插入字符串
string s1 = "zal。。。。";
cout << "s1= " << s1 << endl;
s1.insert(3, "赵阿龙");
cout << "s1= " << s1 << endl;
//2.删除
//利用eraser在当前字符串删除从第n项字符开始的m个元素
s1.erase(0, 3);
cout << "s1= " << s1 << endl;
}
int main()
{
stringout();
}
运行结果
6.从字符串中获取想要的子串
#include<iostream>
#include<string>
using namespace std;
//从字符串中获取想要的子串
void stringout()
{
//利用substr截取从第m个字符开始的n个字符的子串
string s1 = "zhaoAl";
cout << "s1= " << s1 << endl;
string s2 = s1.substr(1, 3);
cout << "s2= " << s2 << endl;
}
int main()
{
stringout();
}
运行结果·
注:string类中的字符串都是从0开始计数的