首页 > 文章列表 > C++ 函数库如何进行字符串操作?

C++ 函数库如何进行字符串操作?

c++ 字符串操作
270 2024-04-23

C++ 标准库提供了丰富的字符串操作函数库,包括获取 C 风格字符串 (std::string::c_str())、获取字符串长度 (std::string::size())、检查字符串是否为空 (std::string::empty())、查找子字符串 (std::string::find()) 等基本操作。此外,还有用于修改字符串 (追加、替换、删除) 和比较字符串 (相等性、包含性) 的操作。本实战案例展示了如何从用户读取文本并将其转换为大写。

C++ 函数库如何进行字符串操作?

C++ 函数库中的字符串操作

C++ 标准库提供了丰富的函数库来处理字符串,让开发者可以轻松地执行各种字符串操作。

基本操作

  • std::string::c_str(): 将字符串转换为 C 风格的以空字符结尾的字符数组。
  • std::string::size(): 返回字符串的字符数。
  • std::string::empty(): 检查字符串是否为空。
  • std::string::find(): 在字符串中查找子字符串。

字符串修改

  • std::string::append(): 将另一个字符串追加到当前字符串。
  • std::string::replace(): 用新字符串替换当前字符串中的子字符串。
  • std::string::erase(): 从当前字符串中删除子字符串或字符。
  • std::string::operator+operator+=: 连接两个字符串。

字符串比较

  • std::string::compare(): 比较两个字符串。
  • std::string::operator==operator!=: 检查两个字符串是否相等或不相等。
  • std::string::find_first_of(): 在字符串中查找特定字符或字符集。

实战案例

让我们创建一个程序,从用户读取一行文本并将其转换为大写。

#include <iostream>
#include <string>

using namespace std;

int main() {
    // 从用户读取一行文本
    cout << "输入一行文本:" << endl;
    string text;
    getline(cin, text);

    // 将文本转换为大写
    for (size_t i = 0; i < text.size(); i++) {
        text[i] = toupper(text[i]);
    }

    // 输出转换后的文本
    cout << "转换后的文本:" << text << endl;

    return 0;
}

输出:

输入一行文本:
Hello World!

转换后的文本:
HELLO WORLD!