C++之String常用操作

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值