C++学习笔记(二十四)——string

一、std::string

作用:
std::string 是 C++ 标准库中的字符串类,用于存储和操作文本字符串。
它相比 char*(C 风格字符串)提供了更安全灵活高效的字符串操作方式。

特点:

  • 自动管理内存(避免 char* 需要 new/delete)。
  • 支持动态大小变化(无需手动扩展 char[])。
  • 提供丰富的字符串操作函数(如拼接、查找、替换等)。

使用 std::string 需要包含头文件:

#include <string>

二、std::string 的基本操作

(1)创建字符串

示例:

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

int main() {
    string s1 = "Hello";    // 直接赋值
    string s2("World");     // 构造函数
    string s3(s1);          // 拷贝构造
    string s4(5, '*');      // 生成 "*****"

    cout << s1 << " " << s2 << " " << s3 << " " << s4 << endl;

    system("pause");
    return 0;
}

注意:
支持多种初始化方式,包括字符串字面量(双引号内容赋值)、拷贝、填充等。

(2) 读取字符串

示例:

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

void PrintString1()
{
    string s;
    cin >> s;  // 只能读取单词(遇到空格停止)
    cout << s << endl;
}

void PrintString2()
{
    string s;
    getline(cin, s);  // 读取整行 
    cout << s << endl;
}

int main() {
    //PrintString1(); // 读取单词(遇到空格停止)
    PrintString2(); // 读取整行(遇到换行停止)

    system("pause");
    return 0;
}

注意:

  • cin >> s;输入的字符串,以空格或换行作为结束标志;
  • getline(cin, s);输入的字符串,以换行作为结束标志。

(3) 拼接字符串

示例:

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

int main() {
    string s1 = "Hello";
    string s2 = "World";
    string s3 = s1 + " " + s2;  // 拼接
    s1 += "!";  // 追加

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

    system("pause");
    return 0;
}

注意:

  • 字符串拼接,可以使用运算符+=+连接其他字符串

(4) 获取长度

示例:

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

int main() {
    string s = "Hello";
    cout << s.length() << endl;  // 或 s.size()

    system("pause");
    return 0;
}

(5) 访问字符

示例:

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

int main() {
    string s = "Hello";
    cout << s[1] << endl;  // 直接访问字符

    s[0] = 'h';  // 修改字符
    cout << s << endl;

    system("pause");
    return 0;
}

(6) 遍历字符串

示例:

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

int main() {
    string s = "Hello";

    for (char c : s) // 遍历字符串
    {
        cout << c;
    }
    cout << endl;

    system("pause");
    return 0;
}

(7) 比较字符串

示例:

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

int main() {
    string s1 = "Hello";
    string s2 = "Hello";

    if (s1 == s2)
        cout << "相等" << endl;
    else if (s1 < s2)
        cout << "s1 小于 s2" << endl;  // 按字典序比较
    else
        cout << "s1 大于 s2" << endl;

    system("pause");
    return 0;
}

(8) 迭代器遍历 string

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

int main() {
    string s = "Hello";

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

    system("pause");
    return 0;
}

注意:
auto it = s.begin();——使用 auto 自动推导迭代器类型。

三、std::string 的常用函数

函数作用示例
size(), length()获取长度s.length()
empty()是否为s.empty()
clear()清空字符串s.clear()
append()追加字符串s.append("ABC")
insert(pos, str)插入字符串s.insert(1, "ABC")
erase(pos, len)删除子串s.erase(1, 3)
replace(pos, len, str)替换子串s.replace(1, 2, "XY")
substr(pos, len)提取子串s.substr(1, 3)
find(str)查找子串位置s.find("AB")
rfind(str)反向查找s.rfind("AB")

示例:

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

int main() {
    string s = "Hello World";

    s.insert(6, "C++ ");   // 插入 "C++"
    s.erase(5, 1);         // 删除空格
    s.replace(0, 5, "Hi"); // 替换 "Hello" 为 "Hi"

    cout << s << endl;  // 输出 "HiC++ World"

    if (s.find("C++") != string::npos)
    {
        cout << "找到 C++" << endl;
    }
    
    system("pause");
    return 0;
}

注意:

  • string::npos 是C++标准库中std::string类的一个静态成员常量
  • string::npos 通常用于表示在字符串中未找到匹配的位置

四、std::stringchar* 的转换

(1) std::string vs char*

特性std::stringchar*(C 风格字符串)
存储方式自动管理内存手动管理内存new/delete
动态扩展支持不支持
字符串拼接+ 直接拼接strcat()
安全性防止越界可能内存泄漏
使用方便封装了丰富的功能函数调用繁琐

注意:

  • 推荐优先使用 std::string,避免 char* 带来的内存管理问题!
  • std::string兼容 C 风格字符串(c_str()),可与 char* 互相转换

(2) stringchar*

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

int main() {
    string s = "Hello";
    const char* cstr = s.c_str();  // 使用 c_str()

    cout << s << endl;
    cout << cstr << endl;
    
    system("pause");
    return 0;
}

注意:
c_str() 返回 const char*,用于 C 语言兼容性。

(3) char*string

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

int main() {
    const char* cstr = "Hello";
    string s = cstr;  // 直接赋值

    cout << cstr << endl;
    cout << s << endl;
    
    system("pause");
    return 0;
}

五、特殊用法

(1)std::stringstd::vector<char> 互相转换

示例:

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

int main() {
    string s = "Hello";

    // string 转 vector<char>
    vector<char> v(s.begin(), s.end());

    // vector<char> 转 string
    string s2(v.begin(), v.end());

    cout << s2 << endl;  // Hello

    system("pause");
    return 0;
}

注意:
适用于 std::vector<char> 处理字符串数据的情况

(2)std::wstring 处理宽字符

示例:

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

int main() {
    wstring ws = L"你好,C++";  // 宽字符
    wcout.imbue(locale("chs")); // 适配显示宽字符中文输出
    wcout << ws << endl;

    system("pause");
    return 0;
}

注意:

  • wcout.imbue(locale("chs"));用于适配显示宽字符中文输出
  • 用于处理 Unicode(如 UTF-16)字符串
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奕天者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值