C++ String类
在C++中处理文本数据时,std::string
类是一个强大而灵活的工具。相比C风格的字符数组,String类提供了更安全、更方便的字符串处理方式,无需手动管理内存,并提供了丰富的字符串操作函数。
基本概念
std::string
类定义在<string>
头文件中,属于标准库的一部分。它是一个模板类std::basic_string
的特化版本,专门用于处理char
类型字符。
备注
在使用String类之前,需要引入相应的头文件:
cpp
#include <string>
并使用标准命名空间:
cpp
using namespace std; // 或使用std::string
String类的创建与初始化
String对象可以通过多种方式创建和初始化:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
// 1. 默认构造函数 - 创建空字符串
string str1;
// 2. 使用字符串字面量初始化
string str2 = "Hello"; // 赋值方式
string str3("World"); // 构造函数方式
// 3. 拷贝构造
string str4 = str2; // 创建str2的副本
// 4. 使用重复字符创建
string str5(5, 'A'); // 创建包含5个'A'的字符串
// 5. 从C风格字符串的子串创建
const char* cstr = "Hello World";
string str6(cstr, 5); // 从cstr取前5个字符
// 6. 从另一个string的子串创建
string str7 = str3.substr(0, 3); // 从str3取前3个字符
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << endl;
cout << "str3: " << str3 << endl;
cout << "str4: " << str4 << endl;
cout << "str5: " << str5 << endl;
cout << "str6: " << str6 << endl;
cout << "str7: " << str7 << endl;
return 0;
}
输出:
str1:
str2: Hello
str3: World
str4: Hello
str5: AAAAA
str6: Hello
str7: Wor
String类的基本操作
字符串长度和容量
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
cout << "字符串: " << str << endl;
cout << "长度: " << str.length() << endl; // 11
cout << "大小: " << str.size() << endl; // 11 (与length相同)
cout << "容量: " << str.capacity() << endl; // 至少11,但可能更大
cout << "最大大小: " << str.max_size() << endl; // 系统允许的最大字符串大小
cout << "是否为空: " << (str.empty() ? "是" : "否") << endl; // 否
return 0;
}
字符访问
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
// 使用[]运算符访问 (不进行边界检查)
cout << "str[0] = " << str[0] << endl; // H
// 使用at()方法访问 (会进行边界检查)
try {
cout << "str.at(1) = " << str.at(1) << endl; // e
cout << "str.at(10) = " << str.at(10) << endl; // 越界,会抛出异常
} catch (const out_of_range& e) {
cout << "越界访问: " << e.what() << endl;
}
// 首尾字符访问
cout << "首字符: " << str.front() << endl; // H
cout << "尾字符: " << str.back() << endl; // o
return 0;
}
字符串修改
赋值与连接
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "World";
// 赋值
string str3;
str3 = str1;
cout << "str3 = " << str3 << endl; // Hello
// 连接运算符
string str4 = str1 + " " + str2;
cout << "str4 = " << str4 << endl; // Hello World
// append方法
string str5 = "Hello";
str5.append(" ");
str5.append(str2);
cout << "str5 = " << str5 << endl; // Hello World
// += 运算符
string str6 = "Hello";
str6 += " " + str2;
cout << "str6 = " << str6 << endl; // Hello World
return 0;
}
插入与擦除
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World";
// 插入字符串
str.insert(5, " Beautiful");
cout << "插入后: " << str << endl; // Hello Beautiful World
// 擦除部分内容
str.erase(5, 10); // 从位置5开始,擦除10个字符
cout << "擦除后: " << str << endl; // Hello World
// 替换部分内容
str.replace(6, 5, "C++");
cout << "替换后: " << str << endl; // Hello C++
return 0;
}
字符串查找与比较
查找操作
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello World! Welcome to C++ programming.";
// 查找子串的位置
size_t pos = str.find("World");
if (pos != string::npos) {
cout << "'World'在位置: " << pos << endl; // 6
}
// 从特定位置开始查找
pos = str.find("o", 5);
if (pos != string::npos) {
cout << "从位置5开始,'o'首次出现在: " << pos << endl; // 7
}
// 从右向左查找
pos = str.rfind("o");
if (pos != string::npos) {
cout << "'o'最后出现在: " << pos << endl; // 某个位置,取决于实际字符串
}
// 查找字符集中的任意字符
pos = str.find_first_of("aeiou");
if (pos != string::npos) {
cout << "第一个元音字母在: " << pos << endl; // 1 (e in Hello)
}
// 查找不在字符集中的第一个字符
pos = str.find_first_not_of("Hello ");
if (pos != string::npos) {
cout << "首个不属于\"Hello \"的字符在: " << pos << endl; // 6 (W in World)
}
return 0;
}
字符串比较
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "apple";
string str2 = "banana";
string str3 = "apple";
// 使用比较运算符
if (str1 == str3) {
cout << "str1等于str3" << endl; // 会输出
}
if (str1 != str2) {
cout << "str1不等于str2" << endl; // 会输出
}
if (str1 < str2) {
cout << "str1小于str2" << endl; // 会输出 (按字典序比较)
}
// 使用compare方法
int result = str1.compare(str2);
if (result < 0) {
cout << "str1小于str2" << endl; // 会输出
} else if (result > 0) {
cout << "str1大于str2" << endl;
} else {
cout << "str1等于str2" << endl;
}
// 比较子串
if (str1.compare(0, 2, str2, 0, 2) < 0) {
cout << "str1的前2个字符小于str2的前2个字符" << endl;
}
return 0;
}
字符串转换
数值转换
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
// 字符串转换为数值
string str_int = "123";
string str_float = "123.456";
int i = stoi(str_int);
float f = stof(str_float);
double d = stod(str_float);
cout << "转换后的整数: " << i << endl;
cout << "转换后的浮点数(float): " << f << endl;
cout << "转换后的浮点数(double): " << d << endl;
// 数值转换为字符串
int num = 456;
double dbl = 456.789;
string str_from_int = to_string(num);
string str_from_dbl = to_string(dbl);
cout << "整数转字符串: " << str_from_int << endl;
cout << "浮点数转字符串: " << str_from_dbl << endl;
return 0;
}
大小写转换
C++标准库没有直接提供字符串的大小写转换函数,但我们可以使用算法库:
cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "Hello World";
string lower_str = str;
string upper_str = str;
// 转换为小写
transform(lower_str.begin(), lower_str.end(), lower_str.begin(),
[](unsigned char c){ return tolower(c); });
// 转换为大写
transform(upper_str.begin(), upper_str.end(), upper_str.begin(),
[](unsigned char c){ return toupper(c); });
cout << "原始字符串: " << str << endl;
cout << "小写: " << lower_str << endl;
cout << "大写: " << upper_str << endl;
return 0;
}
实际应用案例
案例1: 简单文本编辑器
这个简单的文本编辑器允许用户输入、添加、修改和查找文本:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string text;
string command;
cout << "简易文本编辑器\n";
cout << "命令: add (添加文本), find (查找文本), replace (替换文本), display (显示文本), exit (退出)\n";
while (true) {
cout << "\n输入命令: ";
cin >> command;
if (command == "add") {
string input;
cout << "输入要添加的文本: ";
cin.ignore(); // 忽略之前的换行符
getline(cin, input);
if (!text.empty()) {
text += " ";
}
text += input;
cout << "文本已添加。\n";
}
else if (command == "find") {
string search;
cout << "输入要查找的文本: ";
cin >> search;
size_t pos = text.find(search);
if (pos != string::npos) {
cout << "找到'" << search << "',位置: " << pos << "\n";
} else {
cout << "未找到'" << search << "'。\n";
}
}
else if (command == "replace") {
string old_text, new_text;
cout << "输入要替换的文本: ";
cin >> old_text;
cout << "输入新文本: ";
cin >> new_text;
size_t pos = 0;
int count = 0;
while ((pos = text.find(old_text, pos)) != string::npos) {
text.replace(pos, old_text.length(), new_text);
pos += new_text.length();
count++;
}
cout << "替换了" << count << "处文本。\n";
}
else if (command == "display") {
if (text.empty()) {
cout << "文本为空。\n";
} else {
cout << "当前文本: " << text << "\n";
}
}
else if (command == "exit") {
cout << "退出编辑器。\n";
break;
}
else {
cout << "无效命令。\n";
}
}
return 0;
}
案例2: 单词计数器
这个程序统计输入文本中的单词数量:
cpp
#include <iostream>
#include <string>
#include <sstream>
#include <map>
using namespace std;
int main() {
string text;
cout << "输入一段文本 (Ctrl+D结束): " << endl;
// 读取多行文本
string line;
while (getline(cin, line)) {
text += line + " ";
}
// 统计单词
map<string, int> wordCount;
stringstream ss(text);
string word;
int totalWords = 0;
while (ss >> word) {
// 移除标点符号
if (!word.empty() && ispunct(word.back())) {
word.pop_back();
}
// 转换为小写
transform(word.begin(), word.end(), word.begin(),
[](unsigned char c){ return tolower(c); });
if (!word.empty()) {
wordCount[word]++;
totalWords++;
}
}
// 输出结果
cout << "\n单词统计结果:\n";
cout << "总单词数: " << totalWords << endl;
cout << "不同单词数: " << wordCount.size() << endl;
cout << "\n频率最高的5个单词:\n";
// 将单词按频率排序
multimap<int, string, greater<int>> sortedWords;
for (const auto& pair : wordCount) {
sortedWords.insert({pair.second, pair.first});
}
// 输出前5个高频单词
int count = 0;
for (const auto& pair : sortedWords) {
if (count++ >= 5) break;
cout << pair.second << ": " << pair.first << " 次\n";
}
return 0;
}
总结
C++ String类是一个强大且灵活的字符串处理工具,相比C风格字符串有很多优势:
- 自动内存管理: 不需要担心缓冲区溢出或内存泄露
- 丰富的操作函数: 提供了大量方便的字符串操作函数
- 类型安全: 提供了类型检查和异常处理
- 标准库集成: 可以与其他标准库组件无缝协作
在C++中处理文本数据时,String类应该是你的首选。它不仅能简化代码,还能提高程序的安全性和可靠性。
练习
- 编写一个程序,将用户输入的字符串反转并输出。
- 实现一个函数,统计一个字符串中元音字母的数量。
- 编写一个程序,检查输入的两个字符串是否互为回文(例如"abc"和"cba")。
- 实现一个函数,将一个句子中的单词顺序反转(例如"Hello World"变为"World Hello")。
- 编写一个程序,从用户输入的文本中移除所有数字字符。
学习建议
学习String类时,建议多多实践,尝试不同的字符串操作。查阅C++参考文档以了解更多String类的成员函数和用法。最后,记得在实际项目中使用String类替代C风格字符串,以获得更安全、更方便的字符串处理体验。