include<string>
本文最后更新于13 天前,其中的信息可能已经过时,如有错误请发送邮件到big_fw@foxmail.com

我为你整理了最全且实用的版本,包含构造、增删改查、比较、拼接、查找、替换、子串、转换、内存管理等所有高频操作,代码可直接编译运行,每个操作都带详细注释:

#include <iostream>
#include <string>       // C++ string 核心头文件
#include <algorithm>    // 用于字符串排序、查找(算法相关)
#include <cctype>       // 用于字符大小写转换
#include <sstream>      // 用于字符串与数字互转、分割
#include <vector>       // 辅助存储分割后的字符串

using namespace std;

// 打印分割线,方便查看输出
void printLine() {
    cout << "----------------------------------------" << endl;
}

int main() {
    // ======================================
    // 1. 字符串的构造(所有常见方式)
    // ======================================
    printLine();
    cout << "【1. 字符串构造】" << endl;
    string s1;                // 空字符串
    string s2("hello");       // 从C风格字符串构造
    string s3(s2);            // 拷贝构造
    string s4(5, 'a');        // 5个字符'a' → "aaaaa"
    string s5(s2, 1, 3);      // 从s2的下标1开始,取3个字符 → "ell"
    string s6 = "world";      // 赋值构造
    string s7 = s2 + " " + s6;// 拼接构造 → "hello world"

    cout << "s1: " << s1 << "(空)" << endl;
    cout << "s2: " << s2 << endl;
    cout << "s3: " << s3 << endl;
    cout << "s4: " << s4 << endl;
    cout << "s5: " << s5 << endl;
    cout << "s6: " << s6 << endl;
    cout << "s7: " << s7 << endl;

    // ======================================
    // 2. 基本属性(长度、容量、空判断)
    // ======================================
    printLine();
    cout << "【2. 基本属性】" << endl;
    string s = "hello c++";
    cout << "字符串:" << s << endl;
    cout << "长度(size):" << s.size() << endl;        // 等价于length(),返回字符数
    cout << "长度(length):" << s.length() << endl;    // 和size()完全一致
    cout << "容量(capacity):" << s.capacity() << endl;// 已分配的内存大小(字符数)
    cout << "最大长度(max_size):" << s.max_size() << endl;// 理论最大长度
    cout << "是否为空:" << (s.empty() ? "是" : "否") << endl;
    s.clear(); // 清空字符串
    cout << "清空后是否为空:" << (s.empty() ? "是" : "否") << endl;
    s = "hello c++"; // 恢复原值

    // ======================================
    // 3. 字符访问(下标/at/迭代器)
    // ======================================
    printLine();
    cout << "【3. 字符访问】" << endl;
    // 下标访问(无越界检查,速度快)
    cout << "s[1] = " << s[1] << endl; // 'e'
    // at访问(有越界检查,更安全)
    cout << "s.at(2) = " << s.at(2) << endl; // 'l'
    // 首尾字符
    cout << "首字符:" << s.front() << endl; // 'h'
    cout << "尾字符:" << s.back() << endl;   // '+'

    // 迭代器遍历
    cout << "迭代器遍历:";
    for (string::iterator it = s.begin(); it != s.end(); ++it) {
        cout << *it << " ";
    }
    cout << endl;

    // ======================================
    // 4. 增删改操作
    // ======================================
    printLine();
    cout << "【4. 增删改】" << endl;
    // 4.1 追加/拼接
    s.append(" programming"); // 追加字符串 → "hello c++ programming"
    cout << "append后:" << s << endl;
    s += "!"; // 简化版拼接 → "hello c++ programming!"
    cout << "+=后:" << s << endl;
    s.push_back('~'); // 追加单个字符 → "hello c++ programming!~"
    cout << "push_back后:" << s << endl;

    // 4.2 插入
    s.insert(5, ","); // 在下标5插入"," → "hello, c++ programming!~"
    cout << "insert后:" << s << endl;

    // 4.3 删除
    s.erase(14, 11); // 从下标14开始,删除11个字符 → "hello, c++!~"
    cout << "erase后:" << s << endl;
    s.pop_back(); // 删除最后一个字符 → "hello, c++!"
    cout << "pop_back后:" << s << endl;

    // 4.4 替换
    s.replace(7, 3, "python"); // 从下标7开始,替换3个字符为"python" → "hello, python!"
    cout << "replace后:" << s << endl;

    // 4.5 重置大小
    s.resize(10, '*'); // 重置长度为10,不足补'*' → "hello, pyt*"
    cout << "resize后:" << s << endl;
    s.resize(8); // 重置长度为8,截断 → "hello, p"
    cout << "resize截断后:" << s << endl;
    s = "hello world"; // 恢复简单值,方便后续操作

    // ======================================
    // 5. 字符串比较(所有方式)
    // ======================================
    printLine();
    cout << "【5. 字符串比较】" << endl;
    string a = "apple";
    string b = "banana";
    string c = "apple";

    // 直接比较(==/!=/>/</>=/<=)
    cout << "a == c:" << (a == c ? "是" : "否") << endl;
    cout << "a > b:" << (a > b ? "是" : "否") << endl; // 按ASCII码比较,a(97) < b(98),故否

    // compare函数(返回值:0=相等,<0=当前字符串小,>0=当前字符串大)
    cout << "a.compare(b):" << a.compare(b) << endl; // 负数
    cout << "a.compare(c):" << a.compare(c) << endl; // 0
    cout << "b.compare(a):" << b.compare(a) << endl; // 正数
    cout << "a.compare(1,2,b,0,2):" << a.compare(1,2,b,0,2) << endl; // 比较a[1:2]和b[0:2]

    // ======================================
    // 6. 查找与查找替换
    // ======================================
    printLine();
    cout << "【6. 查找操作】" << endl;
    string s_find = "hello world, hello c++";
    // 查找子串(返回首次出现的下标,未找到返回string::npos)
    size_t pos1 = s_find.find("hello");
    cout << "find(\"hello\"):" << pos1 << endl; // 0
    // 从下标5开始查找
    size_t pos2 = s_find.find("hello", 5);
    cout << "find(\"hello\",5):" << pos2 << endl; // 13
    // 从后往前找
    size_t pos3 = s_find.rfind("hello");
    cout << "rfind(\"hello\"):" << pos3 << endl; // 13
    // 查找单个字符
    size_t pos4 = s_find.find('w');
    cout << "find('w'):" << pos4 << endl; // 6
    // 查找任意一个字符(h/e/l)
    size_t pos5 = s_find.find_first_of("hel");
    cout << "find_first_of(\"hel\"):" << pos5 << endl; // 0
    // 查找第一个不在"hel"中的字符
    size_t pos6 = s_find.find_first_not_of("hel");
    cout << "find_first_not_of(\"hel\"):" << pos6 << endl; // 5(空格)

    // ======================================
    // 7. 子串截取
    // ======================================
    printLine();
    cout << "【7. 子串截取】" << endl;
    string s_sub = "0123456789";
    string sub1 = s_sub.substr(2);     // 从下标2开始到末尾 → "23456789"
    string sub2 = s_sub.substr(2, 4);  // 从下标2开始,取4个字符 → "2345"
    cout << "substr(2):" << sub1 << endl;
    cout << "substr(2,4):" << sub2 << endl;

    // ======================================
    // 8. 字符串与数字互转(高频!)
    // ======================================
    printLine();
    cout << "【8. 字符串与数字互转】" << endl;
    // 8.1 数字转字符串
    int num1 = 123;
    double num2 = 3.14159;
    string s_num1 = to_string(num1);   // int → string
    string s_num2 = to_string(num2);   // double → string
    cout << "123 → string:" << s_num1 << endl;
    cout << "3.14159 → string:" << s_num2 << endl;

    // 8.2 字符串转数字
    string s_int = "456";
    string s_double = "9.876";
    int n1 = stoi(s_int);              // string → int
    long n2 = stol(s_int);             // string → long
    double n3 = stod(s_double);        // string → double
    float n4 = stof(s_double);         // string → float
    cout << "\"456\" → int:" << n1 << endl;
    cout << "\"9.876\" → double:" << n3 << endl;

    // ======================================
    // 9. 字符串分割(按分隔符拆分,高频!)
    // ======================================
    printLine();
    cout << "【9. 字符串分割】" << endl;
    string s_split = "apple,banana,orange,grape";
    vector<string> res; // 存储分割结果
    stringstream ss(s_split);
    string temp;
    // 按','分割
    while (getline(ss, temp, ',')) {
        res.push_back(temp);
    }
    cout << "分割\"apple,banana,orange,grape\":";
    for (auto& str : res) {
        cout << str << " ";
    }
    cout << endl;

    // ======================================
    // 10. 大小写转换
    // ======================================
    printLine();
    cout << "【10. 大小写转换】" << endl;
    string s_case = "Hello C++ World!";
    // 转小写
    for (auto& c : s_case) {
        c = tolower(c);
    }
    cout << "转小写:" << s_case << endl;
    // 转大写
    for (auto& c : s_case) {
        c = toupper(c);
    }
    cout << "转大写:" << s_case << endl;

    // ======================================
    // 11. 去除首尾空格(高频!)
    // ======================================
    printLine();
    cout << "【11. 去除首尾空格】" << endl;
    string s_trim = "   hello c++   ";
    // 去除开头空格
    size_t start = s_trim.find_first_not_of(" \t\n");
    // 去除结尾空格
    size_t end = s_trim.find_last_not_of(" \t\n");
    string s_trimmed = (start == string::npos) ? "" : s_trim.substr(start, end - start + 1);
    cout << "原字符串:\"" << s_trim << "\"" << endl;
    cout << "去空格后:\"" << s_trimmed << "\"" << endl;

    // ======================================
    // 12. 其他实用操作
    // ======================================
    printLine();
    cout << "【12. 其他操作】" << endl;
    string s_swap1 = "abc";
    string s_swap2 = "123";
    s_swap1.swap(s_swap2); // 交换两个字符串
    cout << "交换后 s_swap1:" << s_swap1 << ",s_swap2:" << s_swap2 << endl;

    string s_copy = "test";
    char buf[10];
    s_copy.copy(buf, 3, 0); // 从下标0开始,拷贝3个字符到buf
    buf[3] = '\0'; // 手动加结束符(copy不会自动加)
    cout << "copy(buf,3,0):" << buf << endl;

    printLine();
    return 0;
}

编译运行说明

  1. 将代码保存为 string_all.cpp
  2. 使用 g++ 编译:g++ string_all.cpp -o string_all
  3. 运行程序:./string_all(Linux/Mac)或 string_all.exe(Windows)。

总结

这份代码覆盖了 C++ std::string所有核心场景,关键要点:

算法扩展:结合 <algorithm> 可实现排序、去重等更多操作(如 sort(s.begin(), s.end()) 可对字符串字符排序)。

std::string 是 C++ 封装的字符串类,无需手动管理内存,比 C 风格字符串更安全;

高频操作:拼接(+)、比较(==)、查找(find)、子串(substr)、数字互转(to_string/stoi)、分割、去空格

安全建议:优先用 at() 访问字符(有越界检查),而非下标 []

文末附加内容
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇