3. 字符串相关的运算符

C++ 的 std::string 字符串可以直接使用 + 运算符进行拼接操作,也可以使用 == 直接比较两个字符串的内容是否相同。这大大方便了字符串的基本运算操作。

以下列出了常用的字符串操作的运算符。

字符串常用的运算符操作

运算符
说明
+
用于拼接两个字符串(string)或一个字符串(string)一个 char * 字符串的拼接。
==
比较两个字符串是否相等。
!=<<=>>=
用于字符串比较,并返回布尔类型(bool)的数据。(C++20标准已经将其删除)。
[]
用于访问字符串中指定位置的字符。
<<
用于 std::cout 流对象的输出。
>>
用于 std::cin 流对象的输入。

示例

// filename: string_operator.cpp
#include <iostream>

using namespace std;

int main(int argc, char * argv[]) {
    string s1 = "hello";
    string s2 = "world!";
    string s3;
    s3  = s1 + " " + s2; // 字符串拼接

    cout << s3 << endl;
    if (s1 == "hello")
        cout << "s1 字符串的内容是 \"hello\"" << endl;
    else
        cout << "s1 字符串的内容不是 \"hello\"" << endl;

    return 0;
}

编译和运行结果如下:

weimz@mzstudio:~$ g++ -o string_operator string_operator.cpp
weimz@mzstudio:~$ ./string_operator 
hello world!
s1 字符串的内容是 "hello"

实验

尝试下面的运算符操作是否能够成功?想想为什么?

#include <iostream>

using namespace std;

int main(int argc, char * argv[]) {
    // 1. string 字符串和字符串拼接
    string s1 = "ABC";
    string s2 = "123";
    cout << s1 + s2 << endl;
    // 2. string 字符串和 const char *字符串拼接
    cout << s1 + "abc" << endl;
    // 3. const char *字符串和 string 字符串拼接
    cout << "abc" + s1 << endl;
    // 4. const char *字符串和 const char * 字符串拼接
    cout << "abc" + "123" << endl;

    return 0;
}