16.1.6【string字符存取、插入删除、子串截取】

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;


void test1()
{
    string str = "hello";
    cout << str << endl;

    //read
    for(int i=0; i<str.size(); i++)
    {
        cout << str[i] << " ";
    }
    cout << endl;

    for(int i=0; i<str.size(); i++)
    {
        cout << str.at(i) << " ";
    }
    cout << endl;

    //write
    str[0] = 'u';
    cout << str << endl;

    str.at(1) = 'u';
    cout << str << endl;
}


void test2()
{
    string str = "world";

    str.insert(1, "222"); //在下标1位置插入"222"
    cout << str << endl;

    str.erase(1, 3); //从下标1位置开始删除其后3个字符
    cout << str << endl;
}


void test3()
{
    string str= "hi,c++";
    string ss = str.substr(1, 3); //从下标1位置起截取其后3个字符的子串
    cout << ss << endl;

    string email= "eliauk@hftec.com";
    int pos = email.find("@");
    string username = email.substr(0, pos);
    cout << username << endl;
}


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


     /*
        3.1.8 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个字符
    */
    test2();


     /*
        3.1.9 string子串截取
            string substr(int pos = 0, int n = npos) const; //返回由pos开始的n个字符组成的字符串
    */
    test3();


    system("pause");
    return 0;
}

posted @   yub4by  阅读(98)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示