C/C++[codeup 1805]首字母大写

1805题目描述
对一个字符串中的所有单词,如果单词的首字母不是大写字母,则把单词的首字母变成大写字母。
在字符串中,单词之间通过空白符分隔,空白符包括:空格(’ ‘)、制表符(‘\t’)、回车符(‘\r’)、换行符(‘\n’)。

输入
输入一行:待处理的字符串(长度小于100)。

输出
可能有多组测试数据,对于每组数据,
输出一行:转换后的字符串。

样例输入
if so, you already have a google account. you can sign in on the right.
样例输出
If So, You Already Have A Google Account. You Can Sign In On The Right.
注意
字符串中包含空格,制表符,回车符等等,所以用gets或fgets()来输入
gets() ,fgets(),以’\n’判断输入结束,同时将换行符号写入字符串.
思路:首先字符串首字符,islower()判断是否小写,是改为大写.然后从索引1开始遍历字符串,发现空格或者其他单词间隔的字符,signal = 1; 跳出循环.判断下个字符是否同时满足,小写&&signal == 1(该字符为单词首字母),如果是,signal = 0; 改为大写.如果首字母是大写,只修改signal =0; 如此这般,遍历完即可.

#include <iostream>
#include <cstring>
#include <ctype.h>
using namespace std;
int main() {
    char str[100];
    while(fgets(str, 100, stdin) != NULL) {
        if (islower(str[0])) str[0] -= 32;
        int signal = 0;
        for (int i = 1; i < strlen(str); i++) {
            if (str[i] == ' ' || str[i] == '\t' || str[i] == '\r' || str[i] == '\n') {
                signal = 1;
                continue;
            }
            if (signal && islower(str[i])) {
                str[i] -= 32;
                signal = 0;
            }
            if (isupper(str[i])) signal = 0;
        }
        cout << str;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u014281392/article/details/80722631