C++实现英文句子单词首字母大写

本文提供一个C++程序示例,将输入的英文句子中每个单词的首字母转换为大写,其他字母转换为小写,非字母字符保持不变。

**代码示例:**cpp#include #include using namespace std;

// 函数:将大写字母转换为小写字母char toLowerCase(char c) { return tolower(c);}

// 函数:将小写字母转换为大写字母char toUpperCase(char c) { return toupper(c);}

int main() { char c; bool isNewWord = true; // 新单词即将开始的状态变量

cout << '请输入一句英文,以'.'结束:' << endl;    while ((c = getchar()) != '.') {        if (isNewWord && isalpha(c)) {  // 单词首字母大写            cout << toUpperCase(c);            isNewWord = false;        } else if (!isNewWord && isalpha(c)) {  // 单词内字母小写            cout << toLowerCase(c);        } else {  // 非字母保持不变            cout << c;            isNewWord = true;  // 下一个字符为新单词首字母        }    }

cout << endl;    return 0;}

代码解释:

  1. 头文件: - iostream: 用于输入输出操作。 - cctype: 提供字符处理函数,如 isalpha()tolower()toupper()

  2. 函数 toLowerCase(char c): - 接收一个字符 c 作为参数。 - 使用 tolower(c) 将字符转换为小写并返回。

  3. 函数 toUpperCase(char c): - 接收一个字符 c 作为参数。 - 使用 toupper(c) 将字符转换为大写并返回。

  4. 函数 main(): - char c: 存储输入的字符。 - bool isNewWord = true: 状态变量,指示是否遇到新单词,初始值为 true。 - 使用 cout 提示用户输入以 '.' 结束的英文句子。 - while ((c = getchar()) != '.'): 循环读取字符直到遇到 '.'。 - if (isNewWord && isalpha(c)): 如果是新单词且字符是字母: - 使用 toUpperCase(c) 将字符转换为大写并输出。 - 将 isNewWord 设置为 false,表示进入单词内部。 - else if (!isNewWord && isalpha(c)): 如果不是新单词且字符是字母: - 使用 toLowerCase(c) 将字符转换为小写并输出。 - else: 如果是非字母字符: - 直接输出字符。 - 将 isNewWord 设置为 true,表示下一个字符为新单词的开始。 - 最后输出一个换行符。

注意:

  • 该程序使用 getchar() 逐个读取字符,因此不支持包含空格的句子。- 可以使用 cin 和字符串处理函数来支持包含空格的句子。
C++实现英文句子单词首字母大写

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

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