栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ string 的简单总结

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ string 的简单总结

#include "iostream"
#include "string"
using namespace std;

int main() {
    // 初始化
    string a0;  // empty string
    string a1 = "1234";
    string a2(a1);  // copy a1
    string a3(a1, 1);  // from position1 to end  "234"
    string a4(a1, 1, 2);  // start at position1 ,length = 2  "23"
    string a5(5, 'c');  // "ccccc"

    // 赋值操作,使用assign 和 =
    string a;
    a = "123";  // output "123"
    a.assign("12345");  // output "12345"
    a.assign("12345",3);  // 从头开始长度为3的子串 output "123"
    a.assign("123456", 1, 3);  // 从1下标开始长度为3的子串 output "234"
    a.assign("123456", 1, string::npos);  // 从1下标开始到结尾的子串 output "23456"

    // 交换
    string b = "1212";
    swap(a, b);  // 交互相换内容,其实也是一种赋值方式。

    // 尾部插入
    a = "123";
    a += '1';
    a += "123";  // 既可以插入char,也可以插入string

    a = "12";
    a.append("ab");  //append 也是尾插,但是只支持string,要加单个字符的话也得是string。
    a.append("123",1,2);  // 插入从下标1开始长度为2的子串
    a.append("123", 1, string::npos);  // 从下标1开始到结尾的子串
    a.append(5, 'c');  // 插入5个'c'
    a.append("123",2);  // 插入从头开始长度为2的子串

    a.push_back('c');  // push_pack 尾部插入,只支持char

    // 中间插入
    a.insert(1,"123");  // 必须插入字符串,不能插入char

    // 替换
    a = "1234";
    a.replace(1,2,"aa");  // 从下标1开始,长度为2的子串替换为"aa" 屌!

    // 清除
    a = "1234";
    a.erase(1);  // 从1开始全部清除
    a.erase(1,2);  // 从1开始清除长度为2的子串
    a.clear();  // 全部清除

    // 切割
    a = "12345678";
    b = a.substr(3);  // 从下标3开始到结尾切割子串
    b = a.substr(2,4);  // 下标3开始长度为4 切割子串
    b = a.substr();  // copy

    // 比较
    a = "aaa";
    int res;
    res = a.compare("aaa");  // 比较的规则暂时不太明确,数字比大小,字母的话可能比码的大小吧。等于返回0,大于返回1,小雨返回-1;
    a < "aa";  // > < =等 返回值1代表true,0代表false

    // 其余
    a = "1234";
    cout << a.size() << endl; // 4
    cout << a.length() << endl; // 4
    cout << a.max_size() << endl;  // 最大尺寸
    cout << a.empty() << endl; // 0,false 非空
    //暂时整理到这里
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/384501.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号