C++之string

1、标准库string类型

2、string对象的定义和初始化

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

int main() {
    string s1;
    string s2("abcdefghijklmn");
    cout << s2 << endl;

    basic_string<char> s3("xxxx");  // basic_string<char> 等价于string,其实string 就是一个模板,basic_string<char> 是它的原型
    cout << s3 << endl;

    string s4("abcdefg", 4);
    cout << s4 << endl;

    string s5(s2, 2, 3);
    cout << s5 << endl;

    string::iterator first = s2.begin() + 1;
    string ::iterator last = s2.begin() + 3;

    string s6(first, last);  // [first, last)
    cout << s6 << endl;

    return 0;
}

// 输出
abcdefghijklmn
xxxx
abcd
cde
bc

3、常用的成员函数

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

int main() {
    string s1("abcdefghi");
    cout << s1.size() << endl;
    cout << s1.length() << endl;
    cout << s1.empty() << endl;

    cout << s1.substr(1, 2) << endl;
    cout << s1.substr(1) << endl;

    string::size_type pos = s1.find('d', 1);
    if(pos == string::npos)
    {
        cout << "not found" << endl;
    }
    else
    {
        cout << "pos = " << pos << endl;
    }

    pos = s1.rfind('d');
    if(pos == string::npos)
    {
        cout << "not found" << endl;
    }
    else
    {
        cout << "pos = " << pos << endl;
    }

    return 0;
}

// 输出
9
9
0
bc
bcdefghi
pos = 3
pos = 3
#include <string>
#include <iostream>
using namespace std;

int main() {
    string s1("abcdefghijkl");
    s1.replace(2, 2, "AAAAA");
    cout << s1 << endl;

    s1 = "abcdefg";
    s1.replace(s1.begin() + 1, s1.begin() + 4, "BBBBB");
    cout << s1 << endl;

    string s2 = "xyzabc";
    s2.insert(2, "FFFFFF");
    cout << s2 << endl;
    s2.append("7777777777");
    cout << s2 << endl;

    string s3 = "111";
    s2.swap(s3);

    cout << s2 << endl;
    cout << s3 << endl;

    return 0;
}

// 输出
abAAAAAefghijkl
aBBBBBefg
xyFFFFFFzabc
xyFFFFFFzabc7777777777
111
xyFFFFFFzabc7777777777
#include <string>
#include <iostream>
using namespace std;

void fun(char* str)
{
    cout << str << endl;
}
int main() {
    string s1 = "abc";
    s1[1] = 'B';

    cout << s1 << endl;

    const string s2 = "xyz";
    //s2[1] = 'Y';  // function 'operator[]' returns a const value

    string s3 = "132" + s1 + "6547";
    cout << s3 << endl;

    fun(const_cast<char*>(s3.c_str()));
    return 0;
}

// 输出
aBc
132aBc6547
132aBc6547

4、常用的成员函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值