鱼C论坛

 找回密码
 立即注册
查看: 1927|回复: 0

[技术交流] 万行代码计划 Day05

[复制链接]
发表于 2021-7-30 23:44:07 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
万行代码计划
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();
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-21 20:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表