C++ 字符串基础

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习 C++ 中的字符串。你将学习如何定义和初始化字符串,以及如何使用字符串函数。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/BasicsGroup -.-> cpp/arrays("`Arrays`") cpp/BasicsGroup -.-> cpp/strings("`Strings`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/IOandFileHandlingGroup -.-> cpp/user_input("`User Input`") cpp/StandardLibraryGroup -.-> cpp/string_manipulation("`String Manipulation`") cpp/StandardLibraryGroup -.-> cpp/standard_containers("`Standard Containers`") subgraph Lab Skills cpp/data_types -.-> lab-178539{{"`C++ 字符串基础`"}} cpp/arrays -.-> lab-178539{{"`C++ 字符串基础`"}} cpp/strings -.-> lab-178539{{"`C++ 字符串基础`"}} cpp/output -.-> lab-178539{{"`C++ 字符串基础`"}} cpp/user_input -.-> lab-178539{{"`C++ 字符串基础`"}} cpp/string_manipulation -.-> lab-178539{{"`C++ 字符串基础`"}} cpp/standard_containers -.-> lab-178539{{"`C++ 字符串基础`"}} end

内容预览

C++ 支持两种类型的字符串:

  1. 字符串是一个以 NULL 字符 '\0'(十六进制 0)结尾的 char 数组。它也被称为字符字符串或 C 风格字符串(C-style string)。
  2. C++98 引入的新 string 类。

推荐使用“高级”的 string 类,因为它更易于使用和理解。然而,许多遗留程序使用 C 风格字符串;许多程序员也使用“低级”的 C 风格字符串以实现完全控制和高效性;此外,在某些情况下(如命令行参数),仅支持 C 风格字符串。因此,你可能需要同时理解这两种字符串。

  • 字符串的声明和初始化
  • 字符串的输入/输出
  • 字符串操作

字符串的声明和初始化

要使用 string 类,需要包含 <string> 头文件并使用 using namespace std

你可以通过字符串字面量声明和初始化字符串,初始化为空字符串,或者通过另一个字符串对象初始化。例如:

#include <string>
using namespace std;

string str1("Hello");  // 使用字符串字面量初始化(隐式初始化)
string str2 = "world"; // 使用字符串字面量初始化(通过赋值运算符显式初始化)
string str3;           // 初始化为空字符串
string str4(str1);     // 通过复制现有字符串对象初始化

字符串的输入/输出

例如

/* 测试 string 类的输入和输出 */
#include <iostream>
#include <string>     // 需要此头文件以使用 string 类
#include <limits>
using namespace std;  // 也需要用于 <string>

int main() {
   string message("Hello");
   cout << message << endl;

   // 输入一个单词(以空格分隔)到字符串
   cout << "输入一条消息(无空格):";
   cin >> message;
   cout << message << endl;

   cin.ignore(numeric_limits<streamsize>::max(), '\n');
   // 刷新 cin 直到换行符(需要 <limits> 头文件)

   // 输入一行到字符串
   cout << "输入一条消息(带空格):";
   getline(cin, message);  // 从 cin 读取输入到 message
   cout << message << endl;
   return 0;
}

输出:

Hello
输入一条消息(无空格):hello
hello
输入一条消息(带空格):hello world
hello world
图片描述

注意事项:

  • 我们需要 #include <string> 来使用 string 类,并且需要 using namespace std,因为 string 定义在 std 命名空间下。
  • cin >> aStrcin(键盘)读取一个单词(以空格分隔),并将其赋值给 string 变量 aStr
  • getline(cin, aStr)cin 读取整行(直到 '\n'),并将其赋值给 aStr'\n' 字符会被丢弃。
  • 要刷新 cin,你可以使用 ignore(numeric_limits<streamsize>::max(), '\n') 函数来丢弃直到 '\n' 的所有字符。numeric_limits 位于 <limits> 头文件中。

字符串操作

  • 检查字符串的长度:

    string str("Hello, world");
    // 两者都返回字符串的长度
    cout << str.length() << endl;  // 12
    cout << str.size()   << endl;  // 12
  • 检查字符串是否为空:

    string str1("Hello, world");
    string str2;                   // 空字符串
    // 检查字符串是否为空
    cout << str1.empty() << endl;  // 0 (false)
    cout << str2.empty() << endl;  // 1 (true)
  • 从另一个字符串复制:直接使用赋值运算符 =

    string str1("Hello, world"), str2;
    str2 = str1;
    cout << str2 << endl;   // Hello, world
  • 与另一个字符串连接:使用加号 + 运算符,或复合加号 +=

    string str1("Hello,");
    string str2(" world");
    cout << str1 + str2 << endl;  // "Hello, world"
    cout << str1 << endl;         // "Hello,"
    cout << str2 << endl;         // " world"
    str1 += str2;
    cout << str1 << endl;  // "Hello, world"
    cout << str2 << endl;  // " world"
    string str3 = str1 + str2;
    cout << str3 << endl;  // "Hello, world world"
    str3 += "again";
    cout << str3 << endl;  // "Hello, world worldagain"
  • 读取/写入字符串的单个字符:

    string str("Hello, world");
    // 返回索引处的字符,索引从 0 开始。执行索引边界检查。
    cout << str.at(0) << endl;  // 'H'
    cout << str[1] << endl;     // 'e'
    cout << str.at(str.length() - 1) << endl;  // 'd'
    
    str.at(1) = 'a';  // 写入索引 1
    cout << str << endl;  // "Hallo, world"
    
    str[0] = 'h';
    cout << str << endl;  // "hallo, world"
  • 提取子字符串:

    string str("Hello, world");
    // 返回从 beginIndex 开始的子字符串,长度为 size
    cout << str.substr(2, 6) << endl;  // "llo, w"
  • 与另一个字符串比较:

    string str1("Hello"), str2("Hallo"), str3("hello"), str4("Hello");
    cout << str1.compare(str2) << endl;   // 1   'e' > 'a'
    cout << str1.compare(str3) << endl;   // -1  'h' < 'H'
    cout << str1.compare(str4) << endl;   // 0
    
    // 你也可以使用运算符 == 或 !=
    if (str1 == str2) cout << "Same" << endl;
    if (str3 != str4) cout << "Different" << endl;
    cout << boolalpha;  // 将布尔值打印为 true/false
    cout << (str1 != str2) << endl;
    cout << (str1 == str4) << endl;
  • 搜索/替换字符:你可以使用 #include <algorithm> 中的函数。

    例如:

    #include <algorithm>
    ......
    string str("Hello, world");
    replace(str.begin(), str.end(), 'l', '_');
    cout << str << endl;    // He__o, wor_d

示例

/* C++ 字符串函数示例 */
#include <iostream>
#include <string>    // 使用 string 类
using namespace std;

int main() {
   string msg = "hello, world!";
   cout << msg << endl;
   cout << msg.length() << endl;  // 字符串长度
   cout << msg.at(1) << endl;     // 索引 1 处的字符
   cout << msg[1] << endl;        // 同上
   cout << msg.empty() << endl;   // 检查字符串是否为空
   cout << msg.substr(3, 3) << endl; // 从位置 3 开始的子字符串,长度为 3
   cout << msg.replace(3, 3, "why") << endl; // 替换子字符串
   cout << msg.append("end") << endl;        // 在后面追加
   cout << msg + "end" << endl;              // 同上
   cout << msg.insert(3, "insert") << endl;  // 在位置 3 后插入

   string msg1;
   msg1 = msg;   // 复制
   cout << msg1 << endl;

   cout << "输入一行:";
   getline(cin, msg);   // 读取一行输入
   cout << msg << endl;
}

输出:

hello, world!
13
e
e
0
lo,
helwhy world!
helwhy world!end
helwhy world!endend
helinsertwhy world!end
helinsertwhy world!end
输入一行:a
a
图片描述

总结

字符串是除数字之外的另一种重要数据类型。在本节中,我们讨论了字符串的使用,C++ 提供了许多有用的方法来处理字符串,学会轻松使用它们。

您可能感兴趣的其他 C++ 教程