C++中string的一些操作

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
void test()
{
	string s = "abcd";
	//s += "ni";//重载
	/*cout << s << endl;*///abcdni

	char a[20] = "abncd";
	s += (a);//拼接在字符串的后面
	cout << s << endl;
}
void test2() //string拼接
{
	string s = "abcde";
	string s2 = "123";
//s.append(s2);//将s2放在s的后面  abcde123
	s.append(s2,1);//将s2的前n个后 放到字符串s的末尾
	cout << s << endl;
}
void test3() //string 查找  find从前往后找    rfind  最后一次出现的位置
{
	string s = "abcdbc";
	int pos =s.find("bc"); //   查找第一次出现的位置 理解为字符数组 a[0] ='a' [1] ='b' 下标为0
	cout << pos+1 << endl; //按照惯性思维 第二个位置

	int c = s.rfind("bc");
	cout << c +1<< endl;
}
void test4()
{
	string s = "abcdefg";
	s.replace(3, 6, "wxhn");//从3开始的6个字符被替换
	cout << s << endl;

	string s = "abc";
	s.replace(0, 2, "11");//从0开始的两个字符被替换
	cout << s << endl;
}
void test5()
{
	string s = "lynlyn";
	string s2 = "yxj";
	int num = s.compare(s2);//作比较 逐个字符作比较 s比s2大返回1 s比s2小返回-1 相等返回0
	cout << num << endl;
}
void test6()
{
	//string substr(int pos =0,int n = npos)const 返回由pos开始第n个字符组成的字符串
	string s = "abcdefg";
	string n = s.substr(0, 3);//从0开始3个字符
	cout << n << endl;
}
void test7()
{
	string s = "123456";
	s.insert(2, "abc");
	cout << s << endl;
	s.insert(2, "111");//从2号位置前插入111 把改位置往后移 这个字符串插在他的前面 前插
	cout << s << endl;//121113456
	s.erase(0, 2);//从0号位开始删除两个
	cout << s << endl; //1113456
}
int main()
{
	test7();
	return 0;
}

  • 6
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值