Skip to content

C++ 编程入门 - Day 2

引言

在今天的学习中,我们将深入探索 C++ 标准库中的 <string> 头文件。字符串是编程中非常重要的数据类型,C++ 标准库提供了强大的 std::string 类,使字符串操作变得更加简单和高效。


1. <string> 详细介绍

<string> 是 C++ 标准库中专门用于处理字符串的头文件。它定义了 std::string 类,这是一个封装了字符串操作的模板类。

std::string 的特点:

  • 动态大小:字符串的长度可以动态变化
  • 内存管理:自动管理内存,避免了手动分配和释放内存的麻烦
  • 丰富的成员函数:提供了大量的成员函数,用于字符串操作
  • 类型安全:与 C 风格字符串(char*)相比,更加安全
  • 兼容性:可以与 C 风格字符串相互转换

基本操作:

#include <iostream>
#include <string>

using namespace std;

int main() {
    // 字符串初始化
    string str1; // 空字符串
    string str2 = "Hello"; // 从 C 风格字符串初始化
    string str3(5, 'A'); // 初始化 5 个 'A'
    string str4(str2); // 复制构造

    // 字符串输出
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    cout << "str3: " << str3 << endl;
    cout << "str4: " << str4 << endl;

    // 字符串长度
    cout << "Length of str2: " << str2.length() << endl;
    cout << "Size of str2: " << str2.size() << endl;

    // 字符串拼接
    string greeting = str2 + " " + "World!";
    cout << "Greeting: " << greeting << endl;

    return 0;
}

2. 经典示例

示例 1:字符串反转

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str;
    cout << "Enter a string: ";
    getline(cin, str);

    string reversed_str;
    for (int i = str.length() - 1; i >= 0; i--) {
        reversed_str += str[i];
    }

    cout << "Reversed string: " << reversed_str << endl;

    return 0;
}

示例 2:统计字符串中的字符类型

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main() {
    string str;
    cout << "Enter a string: ";
    getline(cin, str);

    int uppercase = 0;
    int lowercase = 0;
    int digits = 0;
    int others = 0;

    for (char c : str) {
        if (isupper(c)) {
            uppercase++;
        } else if (islower(c)) {
            lowercase++;
        } else if (isdigit(c)) {
            digits++;
        } else {
            others++;
        }
    }

    cout << "Uppercase letters: " << uppercase << endl;
    cout << "Lowercase letters: " << lowercase << endl;
    cout << "Digits: " << digits << endl;
    cout << "Other characters: " << others << endl;

    return 0;
}

示例 3:简单的字符串搜索

#include <iostream>
#include <string>

using namespace std;

int main() {
    string text = "The quick brown fox jumps over the lazy dog";
    string search;

    cout << "Text: " << text << endl;
    cout << "Enter search term: ";
    getline(cin, search);

    size_t position = text.find(search);

    if (position != string::npos) {
        cout << "Found \"" << search << "\" at position " << position << endl;
    } else {
        cout << "Did not find \"" << search << "\"" << endl;
    }

    return 0;
}

3. 常见的问题和回答

问题 1:如何将 std::string 转换为 C 风格字符串?

可以使用 c_str() 成员函数:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "Hello World";
    const char* c_str = str.c_str();

    cout << "C style string: " << c_str << endl;

    return 0;
}

问题 2:如何比较两个字符串?

std::string 重载了比较运算符,可以直接使用 ==!=<><=>= 等运算符:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str1 = "apple";
    string str2 = "banana";

    if (str1 == str2) {
        cout << "str1 equals str2" << endl;
    } else if (str1 < str2) {
        cout << "str1 is less than str2" << endl;
    } else {
        cout << "str1 is greater than str2" << endl;
    }

    return 0;
}

问题 3:如何处理字符串中的空白字符?

可以使用 trim 操作,但需要注意的是,C++ 标准库中没有直接提供 trim 函数,但我们可以自己实现:

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

using namespace std;

string trim(const string& str) {
    auto start = str.begin();
    while (start != str.end() && isspace(*start)) {
        start++;
    }

    auto end = str.end();
    do {
        end--;
    } while (distance(start, end) > 0 && isspace(*end));

    return string(start, end + 1);
}

int main() {
    string str = "   Hello World   ";
    cout << "Original string: \"" << str << "\"" << endl;
    cout << "Trimmed string: \"" << trim(str) << "\"" << endl;

    return 0;
}

总结

在今天的学习中,我们深入探索了 C++ 标准库中的 <string> 头文件和 std::string 类。我们学习了:

  1. std::string 的基本概念和特点
  2. 字符串的初始化和基本操作
  3. 三个经典示例:字符串反转、字符类型统计和简单搜索
  4. 常见问题的解答,包括字符串转换、比较和处理空白字符

std::string 是 C++ 编程中非常重要的类,掌握好字符串操作将为您的编程之旅打下坚实的基础。


练习建议: 1. 实现一个字符串替换功能 2. 编写一个程序,检查字符串是否是回文 3. 实现一个简单的密码强度检测程序,检查密码中是否包含大小写字母和数字