C++ STL String学习

C++ STL String学习

#include<iostream>
#include<string>
using namespace std;
int test_string()
{
	// string类初始化
	string s1 = "aaa";
	string s4 = string("dddd");
	string s2 = string(s1); //s1  s2 互不影响,各有各的内存
	string s3 = string(s1, 0, 2); //从s1的第一个字符开始,拷贝2个字符
	s2 = s2 + "bb";
	s1 = s1 + "ccc";
	cout << s1 << ' ' << s2 <<' '<<s3<<' '<<s4<< endl;

	// string常用操作
	string str = "hello world";//初始化为空串
	char c = s1[0]; //string每个字符对应一个char
	cout << c<<endl;

	//获得substr
	string str1 = str.substr(1);// 从第二个字符到结尾
	cout << str1 << endl;
	str1 = str.substr(1, 6); //从第二个字符往后6个字符
	cout << str1 << endl;

	//插入 insert
	str1.insert(1, "s"); //在第2个字符插入字符串
	cout << str1 << endl;
	str1.insert(1, 1, 'z');//在第2个字符后插入字符z一次
	cout << str1<<endl;

	//删除 erase
	str1.erase(5, 2); //在第6个字符删除2个字符
	cout << str1 << endl;
	string::iterator it = str1.begin();
	str1.erase(str1.begin()); //删除迭代器指向的字符
	cout << str1 << endl;
	str1.erase(str1.begin() + 2, str1.end() - 1); //删除之间字符 第三个和倒数第二个字符之内的字符(包括)
	cout << str1 << endl;

	//在末尾增加 append 相当于+=
	str1.append("hello", 2, 3); //从第3个字符开始,三个字符
	cout << str1 << endl;
	s1 = "world";
	str1.append(s1, 2); //增添s1第三个字符到结尾
	cout << str1 << endl;

	//替代 replace
	str1.replace(0, 3, "you"); //012三个字符被you替换
	cout << str1 << endl;

	//string 重载了运算符 < > ==
	 
	//find 发现子串或字符第一次/最后一次出现的位置
	s1 = "worldo";
	cout<<s1.find('o')<<endl;  //输出为1 同s1.find("or")
	cout << s1.rfind('o') << endl; //从后往前找结果为 5

	//数值转换
	int a = 256;
	string as = to_string(a);
	cout << as << endl;
	cout << "字符串转换为10进制整数:" << stoi(as, 0) << endl;

	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43868436/article/details/89676971