1.string基本概念
2.string构造函数
构造函数原型:
string(); 创建一个空的字符串
string(const char*s); 使用字符串s初始化
string(const string& str); 使用一个string对象初始化另一个string对象
string(int n,char c); 使用n个字符c来初始化
代码:
#include<iostream>
using namespace std;
#include<string>
void test()
{
const char *str="hello world";
string s2(str);
cout<<s2<<endl;
string s3(s2);
cout<<s3<<endl;
string s4(5,'a');
cout<<s4<<endl;
}
int main()
{
test();
system("pause");
return 0;
}
3.string-赋值操作
string赋值方式 :1.等号赋值 2.assign赋值
代码:
#include<iostream>
using namespace std;
#include<vector>
//string赋值方式 :1.等号赋值 2.assign赋值
void test()
{
//1.等号赋值
string str1;
str1="hello world";
cout<<"str1= "<<str1<<endl;
string str2;
str2=str1;
cout<<"str2= "<<str2<<endl;
string str3;
str3='a';
cout<<"str3= "<<str3<<endl;
//2.assign赋值
string str4;
str4.assign("I love you");
cout<<"str4= "<<str4<<endl;
string str5;
str5.assign(str4);
cout<<"str5= "<<str5<<endl;
string str6;
str6.assign("I love you",5);
cout<<"str6= "<<str6<<endl;
string str7;
str7.assign(10,'l');
cout<<"str7= "<<str7<<endl;
}
int main()
{
test();
system("pause");
return 0;
}
4. string字符串拼接
函数原型
string& operator+=(const char* str); //重载+=操作符
string& operator+=(const char c); //重载+=操作符
string& operator+=(const string& str); //重载+=操作符
string& append(const char *s); //把字符串s连接到当前字符串结尾
string& append(const char *s,int n); //把字符串s的前n个字符连接到当前字符串的结尾
string& append(const string &s); // 同operator+=(const string& str)
string& append(const string &s,int pos,int n); //字符串s中从pos开始的n个字符连接到字符串的结尾
代码:
#include<iostream>
using namespace std;
#include<vector>
void test()
{
//1
string str1;
str1+="YOU";
cout<<"str1= "<<str1<<endl;
//2.
str1+='cc';
cout<<"str1= "<<str1<<endl;
//3.
string str2="like me";
str1+=str2;
cout<<"str1= "<<str1<<endl;
//4.
string str3="I";
str3.append(" love ");
cout<<"str3= "<<str3<<endl;
//5.
str3.append("games",4);
cout<<"str3= "<<str3<<endl;
}
int main()
{
test();
system("pause");
return 0;
}