C++ :String的使用方法(介绍、声明初始化、编码集、string接口的应用)
String的使用方法(介绍、声明初始化、编码集、string接口应用(迭代器、增容、reserve、resize、operator[ ]、追加(append、+=)、insert、erase、swap、replace、substr、®find))
简单介绍
- string是表示字符串的字符串类
- 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操作。
- string在底层实际是:basic_string模板类的别名,typedef basic_string<char, char_traits, allocator> string;
- 不能操作多字节或者变长字符的序列。
在使用string类时,必须包含头文件以及using namespace std;
使用场合:
string是C++标准库的一个重要的部分,主要用于字符串处理。可以使用输入输出流方式直接进行操作,也可以通过文件进行操作。
声明和初始化方法:
使用 string 时要在头文件当中加入 < string > ,以及命名空间 using namespace std;
声明方式也很简单
声明:
string s1; //声明一个string 对象
string s2[5]; //声明一个string对象的数组
初始化
使用等号的初始化——>做拷贝初始化
不使用等号的初始化——>直接初始化
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s; //默认初始化,一个空的字符串
string s1("ABCD"); //定义一个字符串,内容是“ABCD”
string s2(s1); //把s1拷贝构造给s2
string s3=s2; //把s2拷贝构造给s3(构造+拷贝构造+优化),不建议用,过于复杂
string s4(10,'c'); //把s4初始化成10个c’
string s5="hello"; //拷贝初始化成“hello”
string s6=string(10,'c'); //拷贝初始化:把10个c的字符串拷给s6
char s[]="1234567";
string s7(s,3); //将s的前3个字符复制到s7中
string s8="asac";
string s9(s8,2); //从s8的第二个字符开始到s8完,拷贝给s9
string s10="hello world";
string s11(s10,3,4); //从s10下标3开始拷贝4个字符给s11
return 0;
}
代码实现
#include <iostream>
#include <string>
using namespace std;
void test_string1()
{
// string s1("hello"); //带参的构造函数 ;
typedef basic_string<char> string;
string s2 = "world"; //隐式类型转换(构造+拷贝构造+优化)
char str1[] = "string"; //7
char str2[] = "中国"; //通常一个汉字是两个字节 5
//编码集
char str3[5];
str3[0] = -42;
str3[1] = -48;
str3[2] = -71;
str3[3] = -7;
str3[4] = '\0';
cout << str2 << endl;
cout << str3 << endl;
}
int main()
{
test_string1();
system("pause");
return 0;
}
运行结果:
void test_string2()
{
string s1("hello"); //构造
string s2(s1); //拷贝构造
string s3("world");
s1 = s3; //赋值
cout << s1 << endl; //world
cout << s2 << endl; //hello
cout << s3 << endl; //world
//string(const string& str, size_t pos, size_t len = npos); str的pos位置往后npoed个位置
string s4(s3, 2, 2); //从对象的第2位开始取,取2位
cout << "s4:" << s4 << endl; //s4:rl
string s5(s3, 2); //从对象的第2位开始取,直到‘\0’为止
cout << "s5:" << s5 << endl; //s5:rld
//取字符串的前三位
string path("c:\\test.c", 3); //取字符串的前3位
cout << "The path is" << " " << path << endl; //The path is c:\
//取后缀
string file(