第四章、字符串

当我们在 C 语言中记录字符串数据时,通常使用的是字符型的数组,比如:char mystr[100];,当我们要记录一个常量字符串时通常使用常字符型的指针来指向常量字符串,比如: const char * pstr = "laowei";。在 C 语言中如果将连个字符串拼接成一个更大的字符串就比较麻烦,需要先申请更大的内存空间,然后再使用 strcpy 将第一个字符串复制其中,然后再使用 strcat 将第二个字符串追加到字符串中。

C++ 的标准库给用户提供了一个 string 类型(C++中叫类),它使用动态数组对字符串进行了封装,让字符串的操作更加方便快捷。这个类封装在 std 名字空间中。

1. string 类型

C++ 标准库中的 std::string 在头文件 string 中声明,用于方便地处理字符串,相比C风格字符串数组,它更安全、易用。

下面我们来举例说明他的用法。

示例

// filename: mystring.cpp
#include <iostream>
#include <string>

int main(int argc, const char * argv[]) {
    std::string s1 = "Hello";
    std::string s2 = "World";

    // 拼接
    std::string s3 = s1 + " " + s2 + "!";  // "Hello World!"

    std::cout << "s1:" << s1 << std::endl;
    std::cout << "s2:" << s2 << std::endl;
    std::cout << "s3:" << s3 << std::endl;

    // 获取长度
    std::cout << "字符串s1的长度:" << s1.length() << std::endl;
    std::cout << "字符串s2的长度:" << s2.length() << std::endl;
    std::cout << "字符串s3的长度:" << s3.length() << std::endl;

    return 0;
}

编译和运行结果如下:

weimz@mzstudio:~$ g++ -o mystring mystring.cpp
weimz@mzstudio:~$ ./mystring
s1:Hello
s2:World
s3:Hello World!
字符串s1的长度:5
字符串s2的长度:5
字符串s3的长度:12

可见 C++ 中的 string 类型在存储字符串时非常的方便灵活。

虽然 C++ 提供了 std::string 字符串类型,但如果你不喜欢,你依旧可以使用 C 语言中的字符型数组来存储字符串,因为 C 语言的全部语法和标准库几乎都可以在 C++ 中使用。

实验

使用 sizeof 运算符查看上述 s1s2s3 三个变量的占用的内存空间都是都少?为什么?请使用 AI 工具寻找答案(后面讲解类时才能理解)。