万行代码计划 Day05

万行代码计划
Day05,50行
进度300/10000
有兴趣的伙伴可以一起来,互相监督

/*
0730
list 双向串列
不支持随之访问
插入删除元素很快,不会造成迭代器失效
*/
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <string>
#include <stdexcept>

/*
string和c-style字符串转换
*/

void func(string s) {
    cout << s << endl;
}

void func2(const char *s){
    cout << s << endl;    
}

void test07(){
    string s = "abc";

    const char *p = s.c_str();
    func(p);//const char * 隐式类型转换为 string

    string s2(p);
    //func2(s2);//不存在从 "std::string" 到 "const char *" 的适当转换函数
    func(s2);
}

void test08()
{
	string s = "abcdefg";
	char& a = s[2];
	char& b = s[3];

	a = '1';//会改变s的值
	b = '2';

	cout << s << endl;
	cout << (int*)s.c_str() << endl;

	s = "pppppppppppppp";

	//a = '1';
	//b = '2';

	cout << s << endl;
	cout << (int*)s.c_str() << endl;//地址指向“ppppppppp”

}

/*
string插入和删除操作
string& insert(int pos, const char* s); //插入字符串
string& insert(int pos, const string& str); //插入字符串
string& insert(int pos, int n, char c);//在指定位置插入n个字符c
string& erase(int pos, int n = npos);//删除从Pos开始的n个字符

*/

void test06(){
    string s1("hello");
    s1.insert(1,"111");
    cout << s1 << endl;
    s1.insert(1,s1);
    cout << s1 << endl;
    //删除
    s1.erase(1,3);
    cout << s1 << endl;
}

/*
string子串
string substr(int pos = 0, int n = npos) const;//返回由pos开始的n个字符组成的字符串
*/
//需求  查找一个右键的 用户名
void test05()
{
    string email = "zhangsan@qq.com";
    
    auto pos = email.find('@');
    cout << "pos @ = " << pos << endl;

    auto usrName = email.substr(0,pos);
	cout << "用户名为:" << usrName << endl;
}

/*
string存取字符操作
char& operator[](int n);//通过[]方式取字符
char& at(int n);//通过at方法获取字符

*/
void test02()
{
	string s = "hello world";

	for (int i = 0; i < s.size();i++)
	{
		//cout << s[i] << endl;
		cout << s.at(i) << endl;
	}
	//[] 和at区别?[]访问越界  直接挂掉 at会抛出异常

	try
	{
		cout << s[100] << endl;
        cout << "s[100]" << endl;
		cout << s.at(100) << endl;
	}
	catch (out_of_range & e)
	{
		cout << e.what() << endl;
        cout << "s.at(100) error" << endl;
	}
	catch (...)
	{
		cout << "越界异常" << endl;
	}
}

int main()
{
    test07();
    test08();
    test06();
    test05();
    test02();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值