在 C 语言里,字符串就是 char 数组,拼接要 strcat、求长度要 strlen,一不小心还会越界。C++ 标准库带来了 std::string,这些麻烦基本都消失了。这篇带你把 string 的常用操作过一遍。

定义与初始化

用 string 记得包含 <string> 头文件(有些环境会间接带上,显式写上是好习惯):

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

int main()
{
    string s1 = "hello";
    string s2("world");
    string s3 = s1;                 // 拷贝,直接就是独立的一份

    cout << s1 << " " << s2 << endl;   // 输出:hello world
    return 0;
}

拼接与比较

拼接直接用 +,比较直接用 ==、<,不用再记 strcmp 那套返回值:

string a = "hello";
string b = "world";

string c = a + " " + b;      // 拼接
cout << c << endl;           // 输出:hello world

cout << (a == "hello") << endl;   // 输出:1(相等为真)
cout << (a < b) << endl;          // 输出:1(按字典序 h 排在 w 前面)

a += "!!!";                  // 追加到自身末尾
cout << a << endl;           // 输出:hello!!!

常用方法:size、substr、find

string s = "hello world";

cout << s.size() << endl;          // 输出:11(长度)
cout << s.substr(6) << endl;       // 输出:world(从下标 6 取到末尾)
cout << s.substr(0, 5) << endl;    // 输出:hello(从 0 开始取 5 个字符)

size_t pos = s.find("world");      // 查找子串,返回起点下标
cout << pos << endl;               // 输出:6
cout << (s.find("xyz") == string::npos) << endl;   // 输出:1(找不到返回 npos)

和数字互转

标准库提供了现成的转换函数:

string n = to_string(42);      // 数字转字符串
cout << n + "!" << endl;       // 输出:42!

int a = stoi("123");           // 字符串转 int
double d = stod("3.14");       // 字符串转 double
cout << a + 1 << endl;         // 输出:124
cout << d * 2 << endl;         // 输出:6.28

小结

  • string 自动管理内存,拼接、比较直接用 + 和 ==,比 char 数组省心得多
  • 常用三件套:size 求长度、substr 切子串、find 找位置(找不到返回 npos)
  • 数字互转用 to_string / stoi / stod

写 C++ 时,除非要和 C 接口打交道,字符串一律优先用 string,能避开绝大多数内存问题。