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

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

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

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

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

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

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

祝你编程愉快!

相关推荐
热心网友俣先生4 小时前
2025年数学建模国赛C题超详细解题思路
c语言·开发语言·数学建模
We....4 小时前
Java集合---Collection接口和Map接口
java·开发语言
NULL Not NULL4 小时前
ES6+新特性:现代JavaScript的强大功能
开发语言·前端·javascript
jiaway4 小时前
【C语言】第二课 位运算
c语言·开发语言·算法
IT北辰4 小时前
初学者也能懂!用Python做房屋销售数据分析,从0到1上手实战(附源码和数据)
开发语言·python·数据分析
Q741_1474 小时前
C++ 面试高频考点 力扣 153. 寻找旋转排序数组中的最小值 二分查找 题解 每日一题
c++·算法·leetcode·面试·二分查找
时光追逐者4 小时前
.NET 使用 CsvHelper 快速读取和写入 CSV 文件
c#·.net·.net core·csv
蓝倾9764 小时前
1688拍立淘接口对接实战案例
java·开发语言·数据库·python·电商开放平台·开放api接口
或与且与或非4 小时前
Rust+slint实现一个登录demo
开发语言·rust·状态模式