C++之String常用操作

  • Post author:
  • Post category:其他



1-字符串分配 assign()

#include <iostream>
#include <string>
using namespace std;

int main()
{
	
	
	string str1 = "0123456789";
	string str2,str3;
	//assign参数为const char[]数组与const char*不同之处在于,
	//后一位参数分别为截取前3位以及截取3位之后的字符
	str2.assign("0123456",3);
	str3.assign(str1, 3);

	cout << str2 << endl << str3 << endl;;

}


2-字符串拼接

#include <iostream>
#include <string>
using namespace std;

int main()
{
	//使用重载+=符号字符串拼接
	string str1 = "abc";
	string str2 = "123";
	str1 += str2;
	cout << str1 << endl;
	str1 += "DEF";	//追加字符串
	cout << str1 << endl;
	str1 += ';';	//追加单个字符
	cout << str1 << endl;
	
	//使用append函数字符拼接
	//1-截取字符串或数组之前或者之后的字符
	string str5 = "hello",str6;
	str5.append("world12345",5);	//当使用字符数组时,后一位参数会截取前5位,这与之前的assign逻辑相同
	cout << str5 << endl;
	str6 = "thankyou";				//使用const char*时,后一位参数会截取5位之后的字符串
	str5.append(str6,5);
	cout << str5 << endl;
	// 2-截取任意位置的字符
	string str7 = "abc123";
	str5.append(str7,0,3);		//从第0个位置,截取3个字符(任意位置起,截取N个字符)
	cout << str5 << endl;
}


3-字符串查找与替换–find/replace

#include <iostream>
#include <string>
using namespace std;

int main()
{
	//字符串查找--find()函数
	string str1 = "0123456789";

	//find和rfind的区别在于查找方向的不同,应用于查找相同字符
	auto pos1 = str1.find("6");
	if (pos1!=-1)
		cout << pos1 << endl;

	auto pos2 = str1.rfind("6");
	if (pos2 != -1)
		cout << pos2 << endl;

	//字符串替换replace
	str1.replace(1,3,"ABC"); //从第n和位置起,替换N个字符
	cout << str1 << endl;
}


4-字符串比较cpmpare

#include <iostream>
#include <string>
using namespace std;

int main()
{
	//字符串比较compare
	string str1 = "hello";
	string str2 = "hello";
	string str3 = "hell";

	if (str1.compare(str2)==0)		//返回值==0则字符串相等
	{
		cout << "str1==str2" << endl;
	}

	if (str1.compare(str3) == 0)
	{
		cout << "str1==str3" << endl;
	}
	else
	{
		cout << "str1!=str3" << endl;
	}
}


5-字符串插入与删除

#include <iostream>
#include <string>
using namespace std;

int main()
{
	//字符串插入与删除 insert,erase
	string str1 = "hello";
	str1.insert(1,"555");		//从第N个位置插入字符
	cout << str1 << endl;

	str1.erase(1,3);			//从第N个位置,删除N个字符
	cout << str1 << endl;
	str1.erase(1);				//从第N个位置开始,删除后面字符
	cout << str1 << endl;
}


6-截取字符串substr

#include <iostream>
#include <string>
using namespace std;

int main()
{
	//字符串截取substr--与assign的区别在于,assign会修改字符串,substr则不会
	string str = "abc123";
	auto str1=str.substr(0,3);	//从第N个位置开始,截取N个字符
	cout << str1 << endl;

	string str2 = "zhangsan@163.com";	//小案例截取字email字符串
	auto pos=str2.find('@');

	auto str3=str2.substr(0,pos);
	cout << str3 << endl;
}



版权声明:本文为weixin_43621608原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。