当前位置: 首页 > news >正文

少儿编程C++快速教程之——2. 字符串处理

## 1. 字符串:计算机世界的文字

1.1 什么是字符串?

字符串是由字符组成的序列,就像我们平时说的话或写的句子。在C++中,字符串用string类型表示,可以用来存储名字、地址、句子等各种文本信息。

1.2 创建和使用字符串

#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可以用于输入字符串,但它会在遇到空格时停止读取:

#include <iostream>
#include <string>
using namespace std;int main() {string word;cout << "请输入一个单词: ";cin >> word;cout << "你输入的单词是: " << word << endl;return 0;
}

2.2 使用getline输入整行文本

当我们需要读取包含空格的整行文本时,可以使用getline函数:

#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 处理以特定字符结束的输入

有时候我们需要读取以特定字符(如句点)结束的输入:

#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 处理多个输入

当混合使用cingetline时,需要注意清除输入缓冲区:

#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 手动分割字符串

我们可以使用循环和条件判断来手动分割字符串:

#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类,可以更方便地分割字符串:

#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 实现"我是第几个单词"题目

#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方法来比较字符串:

#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方法可以在字符串中查找子串:

#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 检查字符串是否包含特定内容

#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 统计字符串中的字符

#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 统计每个字母出现的次数

#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 实现垂直柱状图题目

#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 修改字符串内容

#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 替换字符串中的内容

#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 提取子字符串

#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; // 输出: Hellocout << "子字符串2: " << sub2 << endl; // 输出: World!return 0;
}

7. 综合练习

7.1 简单的密码验证器

#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 简单的文本分析器

#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. 下一步学习建议

恭喜你完成了字符串处理的学习!字符串是编程中非常重要的部分,几乎每个程序都会用到字符串处理。接下来你可以:

  1. 多练习:尝试编写更多处理字符串的小程序
  2. 学习正则表达式:更强大的文本匹配和处理工具
  3. 探索字符串算法:如字符串搜索、模式匹配等
  4. 尝试实际项目:如简单的文本编辑器、聊天程序等

记住,字符串处理需要大量练习才能熟练掌握。不要害怕尝试新东西,编程的世界充满了乐趣!

祝你编程愉快!

http://www.dtcms.com/a/366734.html

相关文章:

  • SMARTGRAPHQA —— 基于多模态大模型的PDF 转 Markdown方法和基于大模型格式校正方法
  • Unity之安装教学
  • GcWord V8.2 新版本:TOA/TA字段增强、模板标签管理与PDF导出优化
  • 无需任何软件禁用 10 年 windows 更新
  • ArcGIS答疑-如何消除两张栅格图片中间的黑缝
  • 《D (R,O) Grasp:跨机械手灵巧抓取的机器人 - 物体交互统一表示》论文解读
  • 零售消费企业的数字化增长实践,2025新版下载
  • 三目摄像头 是一种配备三个独立摄像头模块的视觉系统
  • 苍穹外卖Day9 | 用户端、管理端接口功能开发、百度地图解析配送范围
  • 算法之二叉树
  • 不用服务器也能监控网络:MyIP+cpolar让中小企业告别昂贵方案
  • Wisdom SSH 是一款集成了强大 AI 助手功能的 SSH 工具,助你高效管理服务器。
  • 以OWTB为核心的三方仓运配一体化平台架构设计文档V0.1
  • 【软件测试】第1章 认识测试
  • Qt实现2048小游戏:看看AI如何评估棋盘策略实现“人机合一
  • OPENCV复习第二期
  • .NET GcPDF V8.2 新版本:人工智能 PDF 处理
  • Lucene 8.7.0 版本的索引文件格式
  • 学习资料1(粗略版)
  • android View详解—自定义ViewGroup,流式布局
  • Android 项目:画图白板APP开发(三)——笔锋(多 Path 叠加)
  • MySQL主从复制之进阶延时同步、GTID复制、半同步复制完整实验流程
  • Html重绘和重排
  • 25高教社杯数模国赛【C题国一学长思路+问题分析】
  • 观测云产品更新 | LLM 监测、查看器、事件中心、监控等
  • void*指针类型转换笔记
  • SpringBoot中 Gzip 压缩的两种开启方式:GeoJSON 瘦身实战
  • k8s基础(未完待续)
  • 拜占庭攻击与投毒攻击
  • Linux编写shell脚本,输入多个原文件名和新文件名,一次对多个文件重命名