C++的字符串处理函数大整合(持续更新)

以下是我个人整理较为详尽的、常用的字符串定义方法和函数处理方法,靠后的几个操作整理的较为简略,改天给它补完 画个饼

#include <iostream>
#include <cstring>
using namespace std;

int main()
{ //定义字符串的两种方式
    string s1 = "hello ";
    string s2("world");
    string s3 = "Nice to meet,";
    string s4("meet. you, too!");
    string s5 = "Nice to ";
    string s6 = "0";
    cout << "s1 = " << s1 << endl;
    cout << "s2 = " << s2 << endl;
    cout << "s3 = " << s3 << endl;
    cout << "s4 = " << s4 << endl
         << endl;

    //连接
    s1 += s2;
    cout << "s1 = strcat(s1, s2) = " << s1 << endl;

    //append在字符串末尾添加str三种常用的方法
    s1.append(4, '1');
    cout << "s1.append(4, '1') = " << s1 << endl; //在字符串str后接n个字符ch
    s3.append(s4, 5, 10);
    cout << "s3.append(s4, 5, 10)  = " << s3 << endl; //在字符串str1后接字符串str2,从第n1位开始,输出n2个字节
    s5.append(s4);
    cout << "s5.append(s4) = " << s5 << endl //在字符串str1后接字符串str2
         << endl;

    //字符串输出时的越界检查
#if 0
    s2 = s1;
    cout << s2 << endl;

    cout << s1[100] << endl;    //输出时若字符串越界,[]不报错,但会输出垃圾值
    cout << s1.at(100) << endl; //输出时会进行越界检查,若越界则会报错
#endif

    //判长
    cout << "strlen(s4 + s5) = " << s5.length() << endl
         << endl;

    //比较,相等输出非0值,不等输出0,这里用bool型数据将输出值强制置为0或1
    bool a = (s1 == s2);
    cout << "strcmp(s1, s2) = " << a << endl;
    a = s3.compare(s4);
    cout << "s3.compare(s4) = " << a << endl;
    a = s3.compare(0, 8, s5, 0, 8);
    //参数从左到右依次为:字符串1,1的起始位置,1要比较的长度,字符串2,2的起始位置,2要比较的长度
    cout << "s3.compare(0, 8, s5, 0, 8) = " << a << endl
         << endl;

    //查找,返回值为查找位 - 1
    int temp = s1.find('l', 0);
    cout << "temp = s1.find('l', 0) = " << temp + 1 << endl;
    temp = s1.rfind('d', 15);
    cout << "temp = s1.rfind('d', 15) = " << temp + 1 << endl
         << endl;

    //交换
    s1.swap(s2);
    cout << "s1, s2交换结果为:" << endl;
    cout << "s1 = " << s1 << endl;
    cout << "s2 = " << s2 << endl
         << endl;

    //提取子串
    s6 = s2.substr(6, 5); //从s的第n1位开始提取n2个字节
    // s6 = s2.substr();
    // s6 = s2.substr(6);
    cout << "s6 = s2.substr(6, 5) = " << s6 << endl
         << endl;

    //替换
    s2.replace(11, 4, "Nice");
    cout << "s2 = s2.replace(11, 4, “Nice”) = " << s2 << endl
         << endl;

    //插入
    s2.insert(11, " Very nice", 6);
    cout << "s2 = s2.insert(11, “ Very nice”, 6) = " << s2 << endl;
    s3.insert(12, 4, '1');
    cout << "s3 = s3.insert(12, 4, '1') = " << s3 << endl
         << endl;

    //删除
    s5.erase(4, 19);
    cout << "s5.erase(4, 19) = " << s5 << endl; //字符串s从第n1位开始删除n2个字节
    s4.clear();
    cout << "s4.clear() = " << s4 << endl; //字符串s1清空

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值