【题目链接】
ybt 1138:将字符串中的小写字母转换成大写字母
OpenJudge NOI 1.7 13:将字符串中的小写字母转换成大写字母
【题目考点】
1. 字符串处理
2. ASCII码
【解题思路】
- 判断一个字符c是不是小写字母
方法1:看字符的ASCII码是否在特定区间:c >= 'a' && c <= 'z'
方法2:使用<cctype> 中的函数islower(c)
- 大小写反转
字符c表示一个字母
大写转小写:c = c - 'A' + 'a'
或tolower(c)
小写转大写:c = c - 'a' + 'A'
或toupper(c)
其中tolower(),toupper()是<cctype>中的函数
【题解代码】
解法1:用字符数组,字符区间
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[105];
cin.get(s, 105);
int len = strlen(s);
for(int i = 0; i < len; ++i)
{
if(s[i] >= 'a' && s[i] <= 'z')
s[i] = s[i] + 'A' - 'a';
}
cout<<s;
return 0;
}
解法2:用string类,<cctype>中的函数
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin, s);
for(int i = 0; i < s.length(); ++i)
{
if(islower(s[i]))
s[i] = toupper(s[i]);
}
cout<<s;
return 0;
}