C++ STL学习(2)

string

列出一些与vector有差别的成员函数:

substr:

    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
        string str;
        str = "asdfghj";
        cout << str.substr(2) << endl;//1.从str[2]起到结束
        cout << str.substr(2, 4) << endl;//2.从str[2]起取四个字符
        cout << str.substr(2, 100) << endl;//3.若后一个参数超过了字符串总长,则同1
        return 0;
    }

compare:

    #include<iostream>
    #include<string>
    using namespace std;
    int main()
    {
        string str;
        str = "asdfghj";
        cout << str.compare("bc") << endl;//若str小于compare的参数,返回-1
        cout << str.compare("asdfghj") << endl;//若str和compare的参数相等,返回0
        cout << str.compare("ab") << endl;//若str大于compare的参数,返回1
        return 0;
    }

find:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    str = "asdfghjasdfghj";
    cout << str.find("asd") << endl;//若查找成功,返回第一个字符的索引
    cout << str.find("asdef", str.find("asd") + 1, 3) << endl;
    //参数二为查找的起始位置,参数三表示截取待查串的长度
    cout << str.find("asdef", str.find("asd") + 1) << endl;//若未找到,返回string::npos
    return 0;
}
//rfind类似,只是从反向开始查找

copy:

#include<iostream>
#include<string>
using namespace std;
int main()
{
    string str;
    char s[20];
    str = "asdfghjasdfghj";
    cout << str << endl;
    str.copy(s, 2, 5);//将str[5]起的2个字符拷入s
    s[2] = '\0';
    cout << s << endl;
    return 0;
}

replace:
用法太多ORZ,以后再填坑吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值