C++ 字符串大小写转换:将小写字母转换为大写字母,将大写字母转换为小写字母
C++ 字符串大小写转换:将小写字母转换为大写字母,将大写字母转换为小写字母
在 C++ 中,我们可以使用 cctype 头文件中的 toupper() 函数将小写字母转换为大写字母,使用 tolower() 函数将大写字母转换为小写字母。
将小写字母转换为大写字母
#include <iostream>
#include <cctype>
using namespace std;
char toUpperCase(char c) {
return toupper(c);
}
int main() {
char lowercase;
cout << '请输入一个小写字母:';
cin >> lowercase;
char uppercase = toUpperCase(lowercase);
cout << '转换后的大写字母是:' << uppercase << endl;
return 0;
}
这个示例中使用了 cctype 头文件中的 toupper() 函数,将小写字母转换为对应的大写字母。在 main() 函数中,首先从用户输入获取一个小写字母,然后调用 toUpperCase() 函数将其转换为大写字母,并将结果输出到屏幕上。
将大写字母转换为小写字母
#include <iostream>
#include <cctype>
using namespace std;
char toLowerCase(char c) {
return tolower(c);
}
int main() {
char uppercase;
cout << '请输入一个大写字母:';
cin >> uppercase;
char lowercase = toLowerCase(uppercase);
cout << '转换后的小写字母是:' << lowercase << endl;
return 0;
}
这个示例同样使用了 cctype 头文件中的 tolower() 函数,将大写字母转换为对应的小写字母。在 main() 函数中,首先从用户输入获取一个大写字母,然后调用 toLowerCase() 函数将其转换为小写字母,并将结果输出到屏幕上。
通过这两个简单的示例,你可以学习如何使用 C++ 代码实现字符串大小写转换。
原文地址: https://www.cveoy.top/t/topic/WeE 著作权归作者所有。请勿转载和采集!