📚 string类概述
为什么需要string类?
C++的string类是一个功能强大的字符串处理工具,比C语言的字符数组更加安全和方便。
- ✅ 自动管理内存:无需担心缓冲区溢出
- ✅ 动态大小:可以随意增长和缩小
- ✅ 丰富的方法:查找、替换、截取等
- ✅ 运算符重载:支持+、==、<等操作
- ✅ 类型安全:编译时检查类型
💡 char数组 vs string类:
• char str[] = "Hello":固定大小,手动管理
• string str = "Hello":动态大小,自动管理
• 现代C++编程推荐使用string类
string的多种初始化方式
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2("World");
string str3;
string str4(5, '*');
string str5 = str1;
string str6 = str1.substr(0, 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;
return 0;
}
string的基本属性
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
cout << "长度:" << str.length() << endl;
cout << "大小:" << str.size() << endl;
cout << "是否为空:" << str.empty() << endl;
cout << "第一个字符:" << str[0] << endl;
cout << "第一个字符:" << str.at(0) << endl;
return 0;
}
⚙️ 字符串基本操作
字符串拼接
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName = "张";
string lastName = "三";
string fullName = firstName + lastName;
cout << "姓名:" << fullName << endl;
string greeting = "你好,";
greeting += fullName;
greeting += "!";
cout << greeting << endl;
string sentence = "I love ";
sentence.append("C++");
sentence.append(" programming");
cout << sentence << endl;
int age = 18;
string info = "年龄:" + to_string(age);
cout << info << endl;
return 0;
}
字符串比较
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "apple";
string str2 = "banana";
string str3 = "apple";
cout << boolalpha;
cout << "str1 == str3: " << (str1 == str3) << endl;
cout << "str1 != str2: " << (str1 != str2) << endl;
cout << "str1 < str2: " << (str1 < str2) << endl;
cout << "str1 > str2: " << (str1 > str2) << endl;
cout << "str1.compare(str2): " << str1.compare(str2) << endl;
cout << "str1.compare(str3): " << str1.compare(str3) << endl;
return 0;
}
字符串遍历
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
cout << "方式1:";
for (int i = 0; i < str.length(); i++) {
cout << str[i] << " ";
}
cout << endl;
cout << "方式2:";
for (char c : str) {
cout << c << " ";
}
cout << endl;
cout << "方式3:";
for (auto it = str.begin(); it != str.end(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
🛠️ 常用字符串方法
查找方法(find系列)
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World! Hello, C++!";
size_t pos1 = str.find("Hello");
cout << "第一次'Hello'位置:" << pos1 << endl;
size_t pos2 = str.find("Hello", 5);
cout << "第二次'Hello'位置:" << pos2 << endl;
size_t pos3 = str.find("Python");
if (pos3 == string::npos) {
cout << "'Python'未找到" << endl;
}
size_t pos4 = str.rfind("Hello");
cout << "最后一次'Hello'位置:" << pos4 << endl;
string vowels = "aeiouAEIOU";
size_t pos5 = str.find_first_of(vowels);
cout << "第一个元音字母位置:" << pos5 << endl;
return 0;
}
截取和替换
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
string sub1 = str.substr(0, 5);
string sub2 = str.substr(7);
cout << "sub1: " << sub1 << endl;
cout << "sub2: " << sub2 << endl;
string str2 = "I like Java";
str2.replace(7, 4, "C++");
cout << str2 << endl;
string str3 = "Hello!";
str3.insert(5, ", World");
cout << str3 << endl;
string str4 = "Hello, World!";
str4.erase(5, 7);
cout << str4 << endl;
return 0;
}
大小写转换
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str = "Hello, World!";
string upper = str;
transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
cout << "大写:" << upper << endl;
string lower = str;
transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
cout << "小写:" << lower << endl;
string title = "hello world";
if (!title.empty()) {
title[0] = toupper(title[0]);
}
cout << "标题格式:" << title << endl;
return 0;
}
🎯 字符串工具箱
选择要执行的操作
选择操作查看结果...
🚀 高级字符串处理
字符串分割
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
vector<string> split1(string str, char delimiter) {
vector<string> tokens;
stringstream ss(str);
string token;
while (getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
vector<string> split2(string str, string delimiter) {
vector<string> tokens;
size_t pos = 0;
string token;
while ((pos = str.find(delimiter)) != string::npos) {
token = str.substr(0, pos);
tokens.push_back(token);
str.erase(0, pos + delimiter.length());
}
tokens.push_back(str);
return tokens;
}
int main() {
string csv = "apple,banana,cherry,date";
cout << "方法1分割结果:";
vector<string> result1 = split1(csv, ',');
for (const auto& s : result1) {
cout << s << " ";
}
cout << endl;
string path = "usr/local/bin/python";
cout << "方法2分割结果:";
vector<string> result2 = split2(path, "/");
for (const auto& s : result2) {
cout << s << " ";
}
cout << endl;
return 0;
}
字符串与数字转换
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "123";
string str2 = "45.67";
string str3 = "FF";
int num1 = stoi(str1);
double num2 = stod(str2);
int num3 = stoi(str3, nullptr, 16);
cout << "stoi(\"123\"): " << num1 << endl;
cout << "stod(\"45.67\"): " << num2 << endl;
cout << "stoi(\"FF\", 16): " << num3 << endl;
string str4 = to_string(456);
string str5 = to_string(78.9);
cout << "to_string(456): " << str4 << endl;
cout << "to_string(78.9): " << str5 << endl;
return 0;
}
实际应用:文本处理
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int countWords(string text) {
stringstream ss(text);
string word;
int count = 0;
while (ss >> word) {
count++;
}
return count;
}
bool isPalindrome(string str) {
string cleaned;
for (char c : str) {
if (c != ' ') {
cleaned += tolower(c);
}
}
int left = 0, right = cleaned.length() - 1;
while (left < right) {
if (cleaned[left] != cleaned[right]) {
return false;
}
left++;
right--;
}
return true;
}
int main() {
string sentence = "Hello World C++ Programming";
cout << "单词数量:" << countWords(sentence) << endl;
string palindrome = "A man a plan a canal Panama";
cout << "是否回文:" << boolalpha << isPalindrome(palindrome) << endl;
return 0;
}
📝 实战练习
📝 理解测试
以下代码的输出是什么?
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
str.insert(2, "XX");
cout << str << endl;
return 0;
}
选择答案查看解析...
💻 综合挑战
题目:编写一个程序,实现以下功能:
1. 输入一段英文文本
2. 统计每个单词出现的次数
3. 找出出现次数最多的单词
4. 将所有单词按字母顺序排序并输出
点击"生成代码框架"查看提示...