
方法一,ASCII码加减转换。观察到大写字母和小写字母的ASCII码相差32,大写字母+32就是小写字母。
#include <cstdio>int main() {char str[1024];scanf_s("%s", str, 1024);for (char* p = str; *p; ++p) {if (*p >= 'A' && *p <= 'Z') {*p += 32;}}printf("%s\n", str);return 0;}
方法二,比特置1。观察到大写字母的ASCII码的第5比特为0,小写字母第5比特是1,所以大写字母将第5比特置1就是小写字母。置1操作可以用按位或来进行。按位或0x20,或者写成十进制的32均可。
#include <cstdio>int main() {char str[1024];scanf_s("%s", str, 1024);for (char* p = str; *p; ++p) {if (*p >= 'A' && *p <= 'Z') {*p |= 0x20;}}printf("%s\n", str);return 0;}
方法三,用函数。实际工程中遇到这种比较通用的问题,还是应该用已有的函数。这里大写转小写可以用tolower()函数,定义在
#include <cstdio>#include <string>#include <iostream>#include <cctype>#include <algorithm>using namespace std;int main() {string a ="AAAbbb";transform(a.begin(), a.end(), a.begin(), ::tolower);cout << a << endl;return 0;}
