C++ 单词首字母大写转换:仅使用 iostream 库

本教程演示如何仅使用 C++ 的 iostream 库将句子中的每个单词转换为首字母大写。

以下是代码示例:

#include <iostream>
#include <cctype>

std::string capitalizeWord(const std::string& word) {
    std::string capitalizedWord = word;
    if (!capitalizedWord.empty()) {
        capitalizedWord[0] = std::toupper(capitalizedWord[0]);
        for (size_t i = 1; i < capitalizedWord.length(); i++) {
            capitalizedWord[i] = std::tolower(capitalizedWord[i]);
        }
    }
    return capitalizedWord;
}

std::string processSentence(const std::string& sentence) {
    std::string processedSentence;
    std::string word;
    for (char ch : sentence) {
        if (std::isalpha(ch)) {
            word += ch;
        } else {
            if (!word.empty()) {
                processedSentence += capitalizeWord(word) + ch;
                word.clear();
            } else {
                processedSentence += ch;
            }
        }
    }
    if (!word.empty()) {
        processedSentence += capitalizeWord(word);
    }
    return processedSentence;
}

int main() {
    std::string sentence;
    char ch;
    while ((ch = getchar()) != '.') {
        sentence += ch;
    }
    
    std::string processedSentence = processSentence(sentence);
    std::cout << processedSentence << std::endl;
    
    return 0;
}

代码解释:

  1. capitalizeWord 函数:

    • 接收一个字符串作为输入。
    • 将第一个字符转换为大写。
    • 将剩余字符转换为小写。
    • 返回转换后的字符串。
  2. processSentence 函数:

    • 接收一个字符串作为输入。
    • 遍历字符串中的每个字符。
    • 如果字符是字母,则将其添加到 word 字符串中。
    • 如果字符不是字母,则将 word 字符串传递给 capitalizeWord 函数进行转换,并将结果添加到 processedSentence 字符串中。
    • 返回处理后的句子。
  3. main 函数:

    • 从用户处读取输入,直到遇到句号 (.)。
    • 调用 processSentence 函数处理输入的句子。
    • 打印处理后的句子。

示例:

输入: hello world. this is a TEST!

输出: Hello World. This Is A Test!

这段代码展示了如何在不使用任何额外库的情况下,仅使用 iostream 库实现 C++ 中的单词首字母大写转换。它提供了一个简单有效的解决方案,可以轻松集成到任何 C++ 程序中。

C++ 单词首字母大写转换:仅使用 iostream 库

原文地址: https://www.cveoy.top/t/topic/VTB 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录