#include <iostream>
#include<string>
#include<cstring>//to_string() 需要用到这个头文件
using namespace std;
int main()
{
    string s;
    cout << "请输入一个字符串: " << endl;
    cin >> s;
    cout << "s: "
         << s << endl<<"第二个字符s.at(2),等同于s[2]: "
         << s.at(2) << endl<<"最后一个字符,等同于 *s.end(): "
         << s.back() << endl<<"第一个字符:"
         << *s.begin() << endl;
    s.clear();
    cout <<"是否为空字符empty(): "<< boolalpha << s.empty() << endl;
    cout << "the S string is: (空字符) " << s << endl;
    cout << "插入字符uio后,the append string is:";
    s.append("uio");
    cout << s << endl;
    string c = "laotie666";
    s.assign(c);
    cout <<"将s指派为c的字符串assign(): "<< s << endl;
    s.erase(6, 3);
    cout << "擦去从第六位开始之后的3个字符的字符串erase(): "<<s << endl;
    cout <<"找到第一次出现tie的下标find(): "<< s.find("tie") << endl;
    s.insert(3, "123");
    cout << "从第三位开始插入123insert(): " << s<<endl;
    s.replace(3,2, "niuB");
    cout << "从第三个位置开始的两个元素替换为niuB:" << s << endl;
    cout << s << endl;
    cout << "npos为字符串末位的下一位(该位不存在),类似于end(),常与find()搭配使用用于判断字符是否出现: ";
    if(s.find('b')==string::npos)
        cout << "没有出现b字符" << endl;
    cout << "pop_back()删除最后一个字符,push_back('一个字符')在末尾增加一个字符" << endl;
    s.pop_back();
    cout << "pop_back(): " << s<<endl;
    s.push_back('q');
    cout << "push_back('q'): " << s<<endl;
    cout << "string运用迭代器循环,分为正向 begin(),end()和反向 rbegin(),rend()这里以反向为例: " << endl;
    string::reverse_iterator it;  //如果是正序begin()和end()需要用到迭代器iterator而不是reverse_iterator
    for (it = s.rbegin(); it != s.rend();++it)
        cout << *it << " ";
    string a = "123", b = "3.14";
    string s1 = "123abc";
    cout << "stoi将字符串转化为整数:如果为小数则舍去小数点后面部分,如果为数字和其它字母的组合则从第一个为数字开始取到非数字的字符的上一位:";
    cout << stoi(a) << " " << stoi(b) << " " << stoi(s1) << endl;
    cout << "swap 交换两个字符串a,b: ";
    swap(a, b);
    cout << a << " " << b << endl;
    cout << "to_string()将其他类型转换为字符串,此时需要头文件cstring:" << endl;
    int d = 54321;
    double pi = 3.2415;
    string str_d = to_string(d),str_pi=to_string(pi);
    cout << str_d<<" "<<str_pi;
}

更多推荐