C++ 标准库(Standard Template Library, STL)是 C++ 的核心组成部分之一,提供了丰富的数据结构和算法。C++标准库中的<string>
是专门用于处理字符串的头文件。它提供了std::string
类,该类是对C风格字符串的封装,并提供了更安全、更易用的字符串操作功能。
字符串变量声明:
std::string str;
字符串初始化:
std::string str = "Hello, World!";
使用+连接字符串:
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2;
常用成员函数:
size():返回字符串的长度。
empty():检查字符串是否为空。
operator[]:通过索引访问字符串中的字符。
substr():获取子字符串。
find():查找子字符串在主字符串中的位置。
replace():替换字符串中的某些字符。
append():在字符串的末尾添加字符或另一个字符串。
assign():给字符串对象赋值。
erase():删除字符串中的一段字符。
compare():比较两个字符串。
swap():交换两个string对象的内容。
reverse():反转字符串中的字符顺序。
示例:
#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;
std::string::size_type pos = modified.find("World");
if (pos != std::string::npos) {
modified.replace(pos, 5, "C++"); // 从位置pos开始,替换5个字符为"C++"
}
std::cout << "Modified greeting: " << modified << std::endl;
return 0;
}