
1.1 什么是字符串?
字符串是由字符组成的序列,就像我们平时说的话或写的句子。在C++中,字符串用string
类型表示,可以用来存储名字、地址、句子等各种文本信息。
1.2 创建和使用字符串
cpp
#include <iostream>
#include <string> // 使用string类型需要包含这个头文件
using namespace std;
int main() {
// 创建字符串
string greeting = "Hello";
string name = "小明";
string message = "欢迎学习C++编程!";
// 输出字符串
cout << greeting << endl;
cout << "你好," << name << "!" << endl;
cout << message << endl;
// 字符串拼接
string fullGreeting = greeting + ", " + name + "! " + message;
cout << fullGreeting << endl;
return 0;
}
小练习: 创建一个程序,让用户输入姓名和年龄,然后输出一条个性化的欢迎消息。
2. 字符串输入:获取用户的文字
2.1 使用cin
输入单个单词
cin
可以用于输入字符串,但它会在遇到空格时停止读取:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string word;
cout << "请输入一个单词: ";
cin >> word;
cout << "你输入的单词是: " << word << endl;
return 0;
}
2.2 使用getline
输入整行文本
当我们需要读取包含空格的整行文本时,可以使用getline
函数:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence;
cout << "请输入一句话: ";
// 清除输入缓冲区中的换行符
cin.ignore();
// 使用getline读取整行
getline(cin, sentence);
cout << "你输入的是: " << sentence << endl;
return 0;
}
2.3 处理以特定字符结束的输入
有时候我们需要读取以特定字符(如句点)结束的输入:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string sentence;
cout << "请输入一句话(以句点结束): ";
// 使用getline并指定终止字符
getline(cin, sentence, '.');
cout << "你输入的是: " << sentence << endl;
return 0;
}
注意: 使用getline(cin, sentence, '.')
会读取直到遇到第一个句点为止,句点本身不会被包含在字符串中。
2.4 处理多个输入
当混合使用cin
和getline
时,需要注意清除输入缓冲区:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
int age;
string name;
cout << "请输入你的年龄: ";
cin >> age;
// 清除输入缓冲区中的换行符
cin.ignore();
cout << "请输入你的全名: ";
getline(cin, name);
cout << "你好," << name << "! 你今年" << age << "岁了。" << endl;
return 0;
}
小练习: 编写一个程序,让用户输入他们的完整地址(可能包含空格),然后显示出来。
3. 字符串分割:把句子拆成单词
3.1 手动分割字符串
我们可以使用循环和条件判断来手动分割字符串:
cpp
#include <iostream>
#include <string>
#include <vector> // 用于存储分割后的单词
using namespace std;
int main() {
string sentence = "This is a book.";
vector<string> words; // 存储单词的容器
string currentWord;
for (char c : sentence) {
if (c == ' ' || c == '.') {
// 遇到空格或句点,将当前单词添加到列表中
if (!currentWord.empty()) {
words.push_back(currentWord);
currentWord = "";
}
} else {
// 将字符添加到当前单词
currentWord += c;
}
}
// 输出所有单词
cout << "句子中的单词:" << endl;
for (int i = 0; i < words.size(); i++) {
cout << i+1 << ". " << words[i] << endl;
}
return 0;
}
3.2 使用字符串流分割
C++提供了stringstream
类,可以更方便地分割字符串:
cpp
#include <iostream>
#include <string>
#include <sstream> // 字符串流头文件
#include <vector>
using namespace std;
int main() {
string sentence = "This is a book.";
vector<string> words;
// 创建字符串流对象
stringstream ss(sentence);
string word;
// 从流中提取单词
while (ss >> word) {
// 去除单词末尾的标点符号
if (!word.empty() && ispunct(word.back())) {
word.pop_back();
}
words.push_back(word);
}
// 输出所有单词
cout << "句子中的单词:" << endl;
for (int i = 0; i < words.size(); i++) {
cout << i+1 << ". " << words[i] << endl;
}
return 0;
}
3.3 实现"我是第几个单词"题目
cpp
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string sentence;
string targetWord;
cout << "请输入一个英文句子(以句点结束): ";
getline(cin, sentence, '.');
cout << "请输入要查找的单词: ";
cin >> targetWord;
// 分割句子成单词
stringstream ss(sentence);
string word;
vector<string> words;
while (ss >> word) {
// 去除单词末尾的标点符号
if (!word.empty() && ispunct(word.back())) {
word.pop_back();
}
words.push_back(word);
}
// 查找目标单词
bool found = false;
for (int i = 0; i < words.size(); i++) {
if (words[i] == targetWord) {
cout << i + 1 << endl; // 输出位置(从1开始计数)
found = true;
break;
}
}
// 如果没找到,输出字符总数
if (!found) {
int totalChars = 0;
for (string w : words) {
totalChars += w.length();
}
cout << totalChars << endl;
}
return 0;
}
小练习: 编写一个程序,统计一句话中有多少个单词,并找出最长的单词。
4. 字符串比较和查找
4.1 比较字符串
我们可以使用==
运算符或compare
方法来比较字符串:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "apple";
string str2 = "banana";
string str3 = "apple";
// 使用 == 运算符
if (str1 == str2) {
cout << "str1 和 str2 相等" << endl;
} else {
cout << "str1 和 str2 不相等" << endl;
}
if (str1 == str3) {
cout << "str1 和 str3 相等" << endl;
} else {
cout << "str1 和 str3 不相等" << 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;
}
return 0;
}
4.2 查找子串
使用find
方法可以在字符串中查找子串:
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "The quick brown fox jumps over the lazy dog";
string word = "fox";
// 查找子串
size_t position = text.find(word);
if (position != string::npos) {
cout << "找到 '" << word << "' 在位置: " << position << endl;
} else {
cout << "未找到 '" << word << "'" << endl;
}
// 查找字符
position = text.find('q');
if (position != string::npos) {
cout << "找到 'q' 在位置: " << position << endl;
}
// 从指定位置开始查找
position = text.find("the", 10); // 从位置10开始查找
if (position != string::npos) {
cout << "从位置10开始找到 'the' 在位置: " << position << endl;
}
return 0;
}
注意: string::npos
是一个特殊值,表示"未找到"。位置从0开始计数。
4.3 检查字符串是否包含特定内容
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string email = "user@example.com";
// 检查是否包含@符号
if (email.find('@') != string::npos) {
cout << "这是一个有效的电子邮件地址" << endl;
} else {
cout << "这不是一个有效的电子邮件地址" << endl;
}
// 检查是否以特定字符串开头
string url = "https://www.example.com";
if (url.find("https://") == 0) {
cout << "这是一个安全的HTTPS链接" << endl;
}
// 检查是否以特定字符串结尾
string filename = "document.txt";
if (filename.find(".txt") == filename.length() - 4) {
cout << "这是一个文本文件" << endl;
}
return 0;
}
小练习: 编写一个程序,检查用户输入的电子邮件地址是否包含@符号和点号(.)。
5. 字符统计:数一数字母出现的次数
5.1 统计字符串中的字符
cpp
#include <iostream>
#include <string>
#include <cctype> // 用于字符处理函数
using namespace std;
int main() {
string text = "Hello World!";
int letterCount = 0;
int digitCount = 0;
int spaceCount = 0;
int otherCount = 0;
for (char c : text) {
if (isalpha(c)) { // 检查是否是字母
letterCount++;
} else if (isdigit(c)) { // 检查是否是数字
digitCount++;
} else if (isspace(c)) { // 检查是否是空格
spaceCount++;
} else { // 其他字符
otherCount++;
}
}
cout << "字母: " << letterCount << endl;
cout << "数字: " << digitCount << endl;
cout << "空格: " << spaceCount << endl;
cout << "其他: " << otherCount << endl;
return 0;
}
5.2 统计每个字母出现的次数
cpp
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string text = "The quick brown fox jumps over the lazy dog";
int letterCount[26] = {0}; // 26个字母的计数器
for (char c : text) {
if (isalpha(c)) { // 如果是字母
c = tolower(c); // 转换为小写
letterCount[c - 'a']++; // 对应字母计数增加
}
}
// 输出每个字母的出现次数
for (int i = 0; i < 26; i++) {
if (letterCount[i] > 0) {
cout << (char)('a' + i) << ": " << letterCount[i] << endl;
}
}
return 0;
}
5.3 实现垂直柱状图题目
cpp
#include <iostream>
#include <string>
#include <cctype>
#include <algorithm> // 用于max_element
using namespace std;
int main() {
string lines[4];
int charCount[26] = {0};
// 读取4行输入
for (int i = 0; i < 4; i++) {
getline(cin, lines[i]);
}
// 统计每个字母出现的次数
for (int i = 0; i < 4; i++) {
for (char c : lines[i]) {
if (isalpha(c)) {
c = toupper(c);
charCount[c - 'A']++;
}
}
}
// 找出最大的计数(柱状图的最大高度)
int maxCount = 0;
for (int i = 0; i < 26; i++) {
if (charCount[i] > maxCount) {
maxCount = charCount[i];
}
}
// 绘制垂直柱状图
for (int row = maxCount; row > 0; row--) {
for (int col = 0; col < 26; col++) {
if (charCount[col] >= row) {
cout << "* ";
} else {
cout << " ";
}
}
cout << endl;
}
// 输出字母行
for (char c = 'A'; c <= 'Z'; c++) {
cout << c << " ";
}
cout << endl;
return 0;
}
小练习: 修改上面的程序,使其能够处理小写字母,并将结果显示为小写字母。
6. 字符串修改和转换
6.1 修改字符串内容
cpp
#include <iostream>
#include <string>
#include <algorithm> // 用于transform
using namespace std;
int main() {
string text = "Hello World!";
// 转换为大写
for (char &c : text) {
c = toupper(c);
}
cout << "大写: " << text << endl;
// 转换为小写
for (char &c : text) {
c = tolower(c);
}
cout << "小写: " << text << endl;
// 使用algorithm库的transform函数
string original = "Hello World!";
string upper, lower;
upper = original;
transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
cout << "使用transform大写: " << upper << endl;
lower = original;
transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
cout << "使用transform小写: " << lower << endl;
return 0;
}
6.2 替换字符串中的内容
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "I like apples and apples are good";
// 替换所有"apples"为"oranges"
size_t pos = text.find("apples");
while (pos != string::npos) {
text.replace(pos, 6, "oranges");
pos = text.find("apples", pos + 1);
}
cout << "替换后: " << text << endl;
return 0;
}
6.3 提取子字符串
cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string text = "Hello World!";
// 提取子字符串
string sub1 = text.substr(0, 5); // 从位置0开始,提取5个字符
string sub2 = text.substr(6); // 从位置6开始,提取到末尾
cout << "子字符串1: " << sub1 << endl; // 输出: Hello
cout << "子字符串2: " << sub2 << endl; // 输出: World!
return 0;
}
7. 综合练习
7.1 简单的密码验证器
cpp
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string password;
cout << "请输入密码: ";
cin >> password;
bool hasUpper = false;
bool hasLower = false;
bool hasDigit = false;
bool hasSpecial = false;
for (char c : password) {
if (isupper(c)) hasUpper = true;
else if (islower(c)) hasLower = true;
else if (isdigit(c)) hasDigit = true;
else hasSpecial = true;
}
if (password.length() < 8) {
cout << "密码太短,至少需要8个字符" << endl;
} else if (!hasUpper) {
cout << "密码必须包含至少一个大写字母" << endl;
} else if (!hasLower) {
cout << "密码必须包含至少一个小写字母" << endl;
} else if (!hasDigit) {
cout << "密码必须包含至少一个数字" << endl;
} else {
cout << "密码强度足够" << endl;
}
return 0;
}
7.2 简单的文本分析器
cpp
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <cctype>
using namespace std;
int main() {
string text;
cout << "请输入一段文本: ";
getline(cin, text);
// 统计字符数
int charCount = text.length();
// 统计单词数
stringstream ss(text);
string word;
int wordCount = 0;
while (ss >> word) {
wordCount++;
}
// 统计句子数(以句点、问号、感叹号结尾)
int sentenceCount = 0;
for (char c : text) {
if (c == '.' || c == '?' || c == '!') {
sentenceCount++;
}
}
cout << "字符数: " << charCount << endl;
cout << "单词数: " << wordCount << endl;
cout << "句子数: " << sentenceCount << endl;
return 0;
}
8. 下一步学习建议
恭喜你完成了字符串处理的学习!字符串是编程中非常重要的部分,几乎每个程序都会用到字符串处理。接下来你可以:
- 多练习:尝试编写更多处理字符串的小程序
- 学习正则表达式:更强大的文本匹配和处理工具
- 探索字符串算法:如字符串搜索、模式匹配等
- 尝试实际项目:如简单的文本编辑器、聊天程序等
记住,字符串处理需要大量练习才能熟练掌握。不要害怕尝试新东西,编程的世界充满了乐趣!
祝你编程愉快!