美文网首页
C++ string

C++ string

作者: 第八区 | 来源:发表于2017-08-29 10:35 被阅读26次

示例

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

int main()
{
    //构造
    string s1 = "s1";
    string s2 = s1;
    string s3(5, 'a');
    string s4(s1);
    cout << "-------构造结果--------" << endl;
    cout << s1 << endl;
    cout << s2 << endl;
    cout << s3 << endl;
    cout << s4 << endl;
    //操作符重载
    cout << "-------操作符重载--------" << endl;
    cout << (s1 == s2) << endl;
    string s5 = s1 + "+s5";
    cout << s5 << endl;
    cout << (s1 > s5) << endl;
    for (int i = 0; i < s5.size(); i++) {
        cout << s5[i] << "|" << s5.at(i) << "  ";
    }
    cout << endl;
    //长度
    cout << "-------s5长度--------" << endl;
    cout << s5.length() << " " << s5.size() << endl;
    //字符串追加
    cout << "-------s5追加--------" << endl;
    s5.append("->append");
    cout << s5 << endl;
    s5.append("->123456", 2, 2);
    cout << s5 << endl;
    //字符串截取
    cout << "-------截取--------" << endl;
    s5 = s5.substr(3, 2);
    cout << s5 << endl;
    cout << "-------s5和s1交换--------" << endl;
    //字符串内容交换
    s5.swap(s1);
    cout << s5 << endl;
    s5.swap(s1);
    //查找
    cout << "-------查找--------" << endl;
    s1 = "abcdabcd123123";
    int index = s1.find('a', 1);
    cout << index << endl;
    index = s1.find("cd", 3);
    cout << index << endl;
    //替换
    cout << "-------替换--------" << endl;
    s1.replace(0, 4, "1234");
    cout << s1 << endl;
    //插入
    cout << "-------插入--------" << endl;
    s1.insert(4, "[insert]");
    cout << s1 << endl;
    //迭代器正向/反向
    cout << "-------迭代器正向/反向遍历--------" << endl;
    for (string::iterator it = s1.begin(); it != s1.end(); it++) {
        cout << *it;
    }
    cout << endl;
    for (string::reverse_iterator it = s1.rbegin(); it != s1.rend(); it++) {
        cout << *it;
    }
    return 0;
}
运行结果.png

相关文章

网友评论

      本文标题:C++ string

      本文链接:https://www.haomeiwen.com/subject/yfcodxtx.html