HDU2026 首字母变大写
问题链接:HDU2026 首字母变大写。
问题描述:参见上述链接。
问题分析:这是一个字符串输入处理问题,也是一个基本的输入处理训练问题。
程序说明:通过这个例子,可以知道C++程序中如何读入一行,如何判定输入结束(文件结束),以及如何用库函数进行字母判定和大小写转换。
如果用C语言来写这个程序,则是另外一番风景,参见后面给出的代码。由于新标准库函数中,gets()不被推荐使用,所有编写了自己的函数mygets()。
AC的C++语言程序如下:
/* HDU2026 首字母变大写 */
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string s;
while(getline(cin, s)) {
if(islower(s[0]))
s[0] = toupper(s[0]);
for(int i=1, len=s.length(); i<len; i++) {
if(s[i-1] == ' ' && islower(s[i]))
s[i] = toupper(s[i]);
}
cout << s << endl;
}
return 0;
}
AC的C语言程序如下:
/* HDU2026 首字母变大写 */
#include <stdio.h>
#define MAXN 100
#define DELTA 'a'-'A'
int mygets(char s[])
{
int i = 0;
char c;
while((c = getchar()) && c != '\n' && c != EOF)
s[i++] = c;
s[i] = '\0';
return i > 0 || c != EOF;
}
int main(void)
{
char s[MAXN+1];
int i;
while(mygets(s)) {
if('a' <= s[0] && s[0] <= 'z')
s[0] -= DELTA;
for(i=1; s[i]!='\0'; i++) {
if(s[i-1] == ' ' && 'a' <= s[i] && s[i] <= 'z')
s[i] -= DELTA;
}
printf("%s\n", s);
}
return 0;
}
浙公网安备 33010602011771号