题目描述:
对一个字符串中的所有单词,如果单词的首字母不是大写字母,则把单词的首字母变成大写字母。 在字符串中,单词之间通过空白符分隔,空白符包括:空格(' ')、制表符('\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.
解题思路:
需要改成大写的字母有这5种:①位于句首的字母;②空格(' ')后的第一个字符;③制表符('\t')后的第一个字符;④回车符('\r')后的第一个字符;⑤换行符('\n')后的第一个字符。需要注意的是不能够直接写成str[i] = str[i]-32; 因为空白符后面的字符可能是数字 会导致WA,需要用到toupper()函数,这样才能够只将位于空白符后的字母转换成大写形式。
AC代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str;
getline(cin,str);
int len = str.length();
for(int i = 0; i < len; i++)
{
if(i == 0)
{
//str[i] = str[i]-32; 这样写会WA,因为句首可能是数字
str[i] = toupper(str[i]);
}
else
{
if(str[i-1]==' ' || str[i-1]=='\t' || str[i-1]=='\r' || str[i-1]=='\n')
{
//str[i] = str[i]-32; 这样写会WA,因为可能这些空白符后的字符可能是数字
str[i] = toupper(str[i]);
}
}
}
cout << str << endl;
return 0;
}