string 容器
·
std::string 是一个专门用于处理字符串的类,它比 C 风格字符串(字符数组)更安全、更易用、功能更强大。
1. 头文件与声明
首先需要包含 <string> 头文件。
#include <iostream>
#include <string> // 必须包含这个头文件
using namespace std;
int main() {
// 声明 string 对象的不同方式
string str1; // 空字符串
string str2 = "Hello"; // 用 C 风格字符串初始化
string str3("World"); // 用构造函数初始化
string str4(5, 'A'); // 包含 5 个 'A' 的字符串:"AAAAA"
string str5 = str2; // 拷贝初始化
return 0;
}
2. 基本操作
字符串连接
string s1 = "Hello"; string s2 = "World"; string s3 = s1 + " " + s2; // "Hello World" s1 += " C++"; // s1 变为 "Hello C++"
访问字符
string str = "Hello"; cout << str[0]; // 输出 'H',使用下标操作符 cout << str.at(1); // 输出 'e',使用 at() 方法(更安全,会检查边界) // 修改字符 str[0] = 'h'; // 字符串变为 "hello"
获取字符串信息
string str = "Hello World"; cout << "Length: " << str.length() << endl; // 11 cout << "Size: " << str.size() << endl; // 11 (与 length() 相同) cout << "Is empty: " << str.empty() << endl; // 0 (false)
3. 常用的成员函数(方法)
查找相关
string text = "Hello World, Welcome to C++";
// find() - 查找子串位置
size_t pos = text.find("World"); // 返回 6
pos = text.find("Python"); // 返回 string::npos (未找到)
// rfind() - 从后向前查找
pos = text.rfind("o"); // 返回 16
// find_first_of() - 查找任何匹配字符的第一个位置
pos = text.find_first_of("aeiou"); // 返回 1 ('e')
// find_last_of() - 查找任何匹配字符的最后一个位置
pos = text.find_last_of("aeiou"); // 返回 20 ('o')
子串操作
string str = "Hello World";
// substr() - 获取子串
string sub1 = str.substr(6); // "World" (从位置6开始到结尾)
string sub2 = str.substr(0, 5); // "Hello" (从位置0开始,长度为5)
// 实际应用:提取文件名和扩展名
string filename = "document.txt";
size_t dotPos = filename.find('.');
string name = filename.substr(0, dotPos); // "document"
string extension = filename.substr(dotPos + 1); // "txt"
修改字符串
string str = "Hello";
// append() - 追加字符串
str.append(" World"); // "Hello World"
// insert() - 插入字符串
str.insert(5, " Beautiful"); // "Hello Beautiful World"
// erase() - 删除部分字符串
str.erase(5, 10); // 从位置5开始删除10个字符 -> "Hello World"
// replace() - 替换部分字符串
str.replace(6, 5, "C++"); // "Hello C++" (将"World"替换为"C++")
// clear() - 清空字符串
str.clear(); // 字符串变为空
比较字符串
string s1 = "apple";
string s2 = "banana";
if (s1 == s2) {
cout << "Strings are equal" << endl;
} else if (s1 < s2) {
cout << s1 << " comes before " << s2 << endl; // 会输出这个
} else {
cout << s1 << " comes after " << s2 << endl;
}
// 也可以使用 compare() 方法
int result = s1.compare(s2);
if (result == 0) {
cout << "Equal" << endl;
} else if (result < 0) {
cout << "s1 < s2" << endl;
} else {
cout << "s1 > s2" << endl;
}
4. 与 C 风格字符串的转换
// string 转 C 风格字符串 string cppStr = "Hello"; const char* cStr = cppStr.c_str(); // 获取只读的 C 风格字符串 // C 风格字符串转 string const char* cStyleStr = "World"; string fromCStr(cStyleStr); // 直接构造
5. 输入输出
string name; // 从控制台输入 cout << "Enter your name: "; getline(cin, name); // 读取整行(包括空格) // cin >> name; // 只读取到第一个空格 cout << "Hello, " << name << "!" << endl;
6. 综合示例
#include <iostream>
#include <string>
using namespace std;
int main() {
// 1. 创建和初始化
string greeting = "Hello, Programming World!";
cout << "Original: " << greeting << endl;
// 2. 访问和修改
cout << "First character: " << greeting[0] << endl;
greeting[7] = 'p'; // Programming -> programming
cout << "After modification: " << greeting << endl;
// 3. 查找操作
size_t pos = greeting.find("World");
if (pos != string::npos) {
cout << "'World' found at position: " << pos << endl;
}
// 4. 提取子串
string sub = greeting.substr(7, 11); // "programming"
cout << "Substring: " << sub << endl;
// 5. 替换操作
greeting.replace(19, 5, "C++"); // 替换"World"为"C++"
cout << "After replacement: " << greeting << endl;
// 6. 字符串连接
string ending = " Have a nice day!";
string finalMessage = greeting + ending;
cout << "Final message: " << finalMessage << endl;
// 7. 大小和容量
cout << "Length: " << finalMessage.length() << endl;
cout << "Is empty? " << (finalMessage.empty() ? "Yes" : "No") << endl;
return 0;
}
7. 实用技巧
// 遍历字符串的每个字符
string text = "Hello";
for (char c : text) {
cout << c << " ";
}
// 输出: H e l l o
// 使用迭代器遍历
for (auto it = text.begin(); it != text.end(); ++it) {
cout << *it;
}
// 转换为大写
for (char &c : text) { // 注意使用引用才能修改原字符串
c = toupper(c);
}
cout << text; // 输出 "HELLO"
// 检查字符串开头或结尾
string filename = "config.ini";
if (filename.ends_with(".ini")) {
cout << "INI file detected" << endl;
}
if (filename.starts_with("config")) {
cout << "Config file" << endl;
}
string 的主要优势:
-
自动内存管理:不需要手动分配和释放内存
-
动态大小:可以根据需要自动调整大小
-
丰富的接口:提供了大量方便的操作方法
-
安全性:边界检查(使用
at()时) -
兼容性:可以轻松与 C 风格字符串互操作
std::string 是 C++ 中最常用和最实用的容器之一,几乎每个 C++ 程序都会用到它。
更多推荐


所有评论(0)