容器:string

以下是对于string容器常用功能和函数的总结
主要包括
1、定义string
2、字符串赋值
3、字符串拼接:str.append()
4、字符串查找:str.find() / str.rfind()
5、字符串替换:str.replace()
6、字符串长度比较:str.compare()
7、字符串存取:str.at()
8、字符串插入:str.insert()
9、字符串删除:str.erase()
10、字符串获取子串:mystr = str.substr()

#include <iostream>
#include <string>

using namespace std;

void test01()
{
    string str = "hello world!";
    cout << "1 定义字符串:str = " << str << endl;
    cout << endl;

    string str1 = str;
    cout << "2 字符串赋值:str1 = " << str1 << endl;
    cout << endl;

    str.append(" hello cpp!");
    cout << "3 字符串拼接:str = " << str << endl;
    /*
    // append(strName, startPoint, charNum)
    str.append(str1,3,2);
    cout << str << endl;
    */
    cout << endl;

    /*
    4 查找和替换
    查找:查找指定字符串是否存在
    替换:在指定的位置替换字符串
    */
    str = "abcdefghde";
    int pos1 = str.find("de");  // 从左向右数,de第一次出现的位置
    int pos2 = str.rfind("de"); // 从右向左数,de第一次出现的位置
    cout << "4.1.1 find:pos1  = " << pos1 << endl;
    cout << "4.1.2 rfind:pos2 = " << pos2 << endl;

    // 从8号位置起的2个字符,替换成"ijlmn"
    str.replace(8,2,"ijlmn"); // replace(startpos, replaceNum, str_replaced)
    cout << "4.2 replace:str = " << str << endl;
    cout << endl;

    /*
    5 字符串长度比较: 比较ASCLL码,最大的作用是比较两个字符串是否相等
    如果 长度相等,返回0,
    如果 长度少n个,返回 -n
    如果 长度大m个,返回 m
    = 返回 0
    > 返回 1
    < 返回 -1
    */
    str = "hello";
    int flag1 = str.compare("hello world");
    int flag2 = str.compare("hel");
    cout << "5.1 compare:flag1 = " << flag1 << endl;
    cout << "5.2 compare:flag2 = " << flag2 << endl; 
    cout << endl; 

    /*
    6 字符的存取
    注:可以对单个字符进行操作
    */
    str = "hello world";
    str.at(1) = 'h';
    str[2] = 'a';
    cout << "6 at:str = " << str << endl;
    cout << "6.2 :str = " << str << endl;
    cout << endl;

    /*
    7 插入和删除
    str.insert(int pos, "str");
    str.erase(int pos, 删除的字符数量)
    */
    str = "hello world";
    str.insert(6,"hi ");
    cout << "7.1 insert:str = " << str << endl;
    str.erase(6,3);
    cout << "7.2 erase :str = " << str << endl;
    cout << endl;

    /*
    8 获取子串,不改变原有字符串
    从字符串中获取想要的子串 substr(起始位置,截取数量)
    */
    str = "hello world";
    string mystr = str.substr(1,4);
    cout << "str = "<< str << endl;
    cout << "8 substr:mystr = " << mystr << endl;
    
}

int main(int argc, char **argv)
{
    test01();
    return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值