C++ string 容器

Hello, 大家好,我是爱吃香蕉的猴子, 写写String的例子


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

//初始化
void test01() {

	string s1; //调用无参构造
	string s2(10, 'a');
	string s3("abcdefg");
	string s4(s3); //拷贝构造


	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
}

//赋值操作
void test02() {

	string s1;
	string s2("appp");
	s1 = "abcdef";
	cout << s1 << endl;
	s1 = s2;
	cout << s1 << endl;
	s1 = 'a';
	cout << s1 << endl;

	//成员方法assign
	s1.assign("jkl");
	cout << s1 << endl;
}

//取值操作
void test03() {


	string s1 = "abcdefg";

	//重载[]操作符
	for (int i = 0; i < s1.size(); i++) {
		cout << s1[i] << " ";
	}
	cout << endl;

	//at成员函数
	for (int i = 0; i < s1.size(); i++) {
		cout << s1.at(i) << " ";
	}
	cout << endl;

	//区别:[]方式 如果访问越界,直接挂了
	//at方式 访问越界 抛异常out_of_range

	try {
		//cout << s1[100] << endl;
		cout << s1.at(100) << endl;
	}
	catch (...) {
		cout << "越界!" << endl;
	}

}

//拼接操作
void test04() {
	string s = "abcd";
	string s2 = "1111";
	s += "abcd";
	s += s2;
	cout << s << endl;


	string s3 = "2222";
	s2.append(s3);
	cout << s2 << endl;


	string s4 = s2 + s3;
	cout << s4 << endl;
}

//查找操作
void test05() {

	string s = "abcdefghjfgkl";
	//查找第一次出现的位置
	int pos = s.find("fg");
	cout << "pos:" << pos << endl;

	//查找最后一次出现的位置
	pos = s.rfind("fg");
	cout << "pos:" << pos << endl;

}


//string替换
void test06() {
	string s = "abcdefg";
	s.replace(0, 2, "111");
	cout << s << endl;
}

//string比较
void test07() {

	string s1 = "abcd";
	string s2 = "abce";

	if (s1.compare(s2) == 0) {
		cout << "字符串相等!" << endl;
	}
	else {
		cout << "字符串不相等!" << endl;
	}

}

//子串操作
void test08() {

	string s = "abcdefg";
	string mysubstr = s.substr(1, 3);
	cout << mysubstr << endl;
}

//插入和删除
void test09() {

	string s = "abcdefg";
	s.insert(3, "111");
	cout << s << endl;

	s.erase(0, 2);
	cout << s << endl;
}

void test10()
{
    //string 转 char*
	string str = "itcast";

	const char* cstr = str.c_str();
	//char* 转string
	const char* strs= "itcast";
	string sstr(strs);
}

int main(void) {

	//test01();
	//test02();
	//test03();
	//test04();
	//test05();
	//test06();
	//test07();
	//test08();
	test09();


	return 0;
}

                                      Code的搬运工V1.0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值