目录
编辑方式一: +=(可追加字符、char*、string类型)
1 基本概念
- string本质上是一个类
- string类内部封装了很多成员方法,例如:查找find、拷贝copy,删除delete,替换replace,插入insert
- string管理char*所分配的内存,不用担心复制越界和取值越界等,由类内部进行负责
1.1 string和char*的区别:
- char*是指针
- string是一个类,类内部封装了char*,管理这个字符串,是一个char*型的容器。
2 string构造函数
函数原型:
- string(); //创建一个空的字符串,例如string str;
- string(const char* s); //使用字符指针s初始化
- string(const string& str); //使用一个string对象初始化另一个string对象
- string(int n, char c); //使用n个字符c初始化
#include <iostream>
#include <string>
using namespace std;
void test01(){
string s1(); //创建一个空的字符串
const char* st1 = "hello world";
string s2(st1); //使用字符串st1初始化s2
const string& st2 = "world";
string s3(st2); //使用一个string对象初始化另一个string对象
int n = 2;
char c = 'x';
string s4(n, c);
cout << "s1 = " << s1 <<endl;
cout << "s2 = " << s2 <<endl;
cout << "s3 = " << s3 <<endl;
cout << "s4 = " << s4 <<endl;
}
int main() {
test01();
return 0;
}
1 = 1
s2 = hello world
s3 = world
s4 = xx
3 string操作
3.1 赋值操作
函数原型:
方式一: =
#include <iostream>
#include <string>
using namespace std;
void test01(){
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;
}
int main() {
test01();
return 0;
}
str1 = hello world
str2 = hello world
str3 = a
方式二: assign
#include <iostream>
#include <string>
using namespace std;
void test01(){
string str4;
str4.assign("hello C++");
cout << "str4 = " << str4 << endl;
string str5;
str5.assign(str4);
cout << "str5 = " << str5 << endl;
string str6;
str6.assign("hello C++", 5);
cout << "str6 = " << str6 << endl;
string str7;
str7.assign(8, 'x');
cout << "str7 = " << str7 << endl;
}
int main()