如何使用C++中的字符串类(如std::string)

在C++中,std::string 类是标准模板库(Standard Template Library, STL)的一部分,它提供了对字符串的灵活处理。std::string 使得字符串的存储、操作、比较、查找等任务变得更加方便和高效。下面将介绍如何使用 std::string 类。

1. 包含头文件

要使用 std::string,首先需要包含其对应的头文件 <string>


  

cpp复制代码

#include <string>

2. 声明和初始化

声明

  

cpp复制代码

std::string str; // 声明一个空字符串
初始化
  • 直接赋值:

  

cpp复制代码

std::string str = "Hello, World!";
  • 使用构造函数:

  

cpp复制代码

std::string str("Hello, World!");
  • 使用 std::string 的其他构造函数,如从字符数组初始化:

  

cpp复制代码

char arr[] = "Hello, World!";
std::string str(arr);

3. 字符串操作

连接字符串

使用 + 操作符或者 append() 成员函数。


  

cpp复制代码

std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string str3 = str1 + str2; // 使用 + 操作符
std::string str4 = "Hello, ";
str4.append("World!"); // 使用 append() 函数
获取字符串长度

使用 size() 或 length() 成员函数。


  

cpp复制代码

std::string str = "Hello, World!";
std::size_t len = str.size(); // 或 str.length();
字符串比较

使用 ==!=<><=>= 操作符或者 compare() 成员函数。


  

cpp复制代码

std::string str1 = "apple";
std::string str2 = "banana";
if (str1 < str2) {
// str1 小于 str2
}
int result = str1.compare(str2); // 如果 str1 小于 str2,返回负值;如果相等,返回 0;如果大于,返回正值。
访问字符串中的字符

使用下标操作符 [] 或 at() 成员函数(at() 会进行越界检查)。


  

cpp复制代码

std::string str = "Hello";
char c = str[0]; // 使用下标操作符
char d = str.at(1); // 使用 at() 函数

4. 修改字符串

替换字符串

使用 replace() 成员函数。


  

cpp复制代码

std::string str = "Hello, World!";
str.replace(7, 5, "C++"); // 从索引 7 开始,替换长度为 5 的子串为 "C++"
插入和删除
  • 插入:使用 insert() 成员函数。

  

cpp复制代码

std::string str = "Hello";
str.insert(5, " World"); // 在索引 5 的位置插入 " World"
  • 删除:使用 erase() 成员函数。

  

cpp复制代码

std::string str = "Hello, World!";
str.erase(7, 5); // 从索引 7 开始,删除长度为 5 的子串

5. 查找字符串

使用 find()rfind()find_first_of()find_last_of()find_first_not_of()find_last_not_of() 等成员函数。


  

cpp复制代码

std::string str = "Hello, World!";
std::size_t pos = str.find("World"); // 查找 "World" 第一次出现的位置

std::string 类提供的功能远不止这些,但以上介绍的是最基本和最常用的操作。通过查阅 C++ 标准库文档,你可以了解到更多高级特性和用法。

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 12:32:05       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 12:32:05       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 12:32:05       45 阅读
  4. Python语言-面向对象

    2024-07-21 12:32:05       55 阅读

热门阅读

  1. Ubuntu 20安装JDK17和MySQL8.0

    2024-07-21 12:32:05       16 阅读
  2. OpenJudge | 约瑟夫问题

    2024-07-21 12:32:05       14 阅读
  3. 在Jupyter Notebook中进行大数据分析:集成Apache Spark

    2024-07-21 12:32:05       16 阅读
  4. webpack

    2024-07-21 12:32:05       20 阅读
  5. 算法剩余部分

    2024-07-21 12:32:05       15 阅读
  6. 【SQL】百万千万级最大表如何添加字段

    2024-07-21 12:32:05       18 阅读
  7. 谓词 & lambda & bind()

    2024-07-21 12:32:05       14 阅读
  8. 系统运维的数字化与智能化探索

    2024-07-21 12:32:05       16 阅读
  9. Python异常处理

    2024-07-21 12:32:05       13 阅读
  10. 力扣题解(完全平方数)

    2024-07-21 12:32:05       20 阅读