C++ 标准库 <string>
C++ 标准库(Standard Template Library, STL)是 C++ 的核心组成部分之一,提供了丰富的数据结构和算法。
<string> 是 C++ 标准库中用于处理字符串的头文件。
在 C++ 中,字符串是由字符组成的序列。<string> 头文件提供了 std::string 类,它是对 C 风格字符串的封装,提供了更安全、更易用的字符串操作功能。
要在 C++ 程序中使用 <string> 库,首先需要包含这个头文件:
#include <iostream>
#include <string>
基本语法
std::string 类的基本语法如下:
声明字符串变量:
std::string str;
初始化字符串:
std::string str = "Hello, World!";
使用 + 连接字符串:
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2;
常用成员函数
std::string 类提供了许多成员函数来操作字符串,以下是一些常用的成员函数:
size():返回字符串的长度。
empty():检查字符串是否为空。
operator[]:通过索引访问字符串中的字符。
substr():获取子字符串。
find():查找子字符串在主字符串中的位置。
replace():替换字符串中的某些字符。
实例
下面是一个使用 <string> 库的简单实例,包括输出结果:
实例
#include <iostream>
#include <string>
int main() {
// 声明并初始化字符串
std::string greeting = "Hello, World!";
std::cout << "Greeting: " << greeting << std::endl;
// 使用 size() 获取字符串长度
std::cout << "Length of the greeting: " << greeting.size() << std::endl;
// 使用 empty() 检查字符串是否为空
std::cout << "Is the greeting empty? " << (greeting.empty() ? "Yes" : "No") << std::endl;
// 使用 operator[] 访问特定位置的字符
std::cout << "Character at position 7: " << greeting[7] << std::endl;
// 使用 substr() 获取子字符串
std::string sub = greeting.substr(7, 5);
std::cout << "Substring from position 7 with length 5: " << sub << std::endl;
// 使用 find() 查找子字符串
std::cout << "Position of 'World' in the greeting: " << greeting.find("World") << std::endl;
// 使用 replace() 替换字符串中的字符
std::string modified = greeting.substr(0, 7) + "C++" + greeting.substr(7 + 5);
std::cout << "Modified greeting: " << modified << std::endl;
return 0;
}
输出结果:
Greeting: Hello, World!
Length of the greeting: 13
Is the greeting empty? No
Character at position 7: W
Substring from position 7 with length 5: orld!
Position of 'World' in the greeting: 7
Modified greeting: Hello, C++!