toupper函数
在 C++ 中,toupper 函数用于将小写字母转换为大写字母。这个函数在<cctype> 头文件中定义,属于 C++ 的 ctype 库。toupper
函数有两种用法:
- 作为函数模板使用,接受一个字符作为参数,并返回该字符的大写形式(如果它是小写字母)。
#include <cctype> // 包含toupper函数
#include <iostream>
using namespace std;
int main() {
char c = 'a'; // 小写字母
cin>>c;
char upper_c = toupper(c); // 转换为大写
cout << "大写字母: " << upper_c << endl;
return 0;
}
2. 作为函数对象使用:接受一个字符和一个 locale
对象作为参数,并返回该字符在该 locale
的大写形式(如果它是小写字母)。这种用法允许程序根据不同的地区设置来转换字符。
#include <cctype> // 包含toupper函数
#include <iostream>
#include <locale> // 包含locale对象
using namespace std;
int main() {
char c ; // 小写字母
cin>>c;
locale loc; // 默认地区设置
char upper_c = toupper(c, loc); // 转换为大写
cout << "大写字母为: " << upper_c <<endl;
return 0;
}
请注意,toupper
函数只对ASCII字符集中的小写字母有效。对于其他字符,它将返回原字符。如果您需要处理其他语言或字符集,您可能需要使用 C++ 的 locale 相关函数。
tolower 函数
同样,在 C++ 中,要将大写字母转换为小写字母,可以使用 <cctype>
头文件中定义的 tolower
函数。这个函数接受一个字符作为参数,如果该字符是大写字母,则返回其对应的小写形式;如果该字符不是大写字母,则直接返回该字符。
tolower函数两种使用方法和toupper函数相同,下面只举一个例子:
1.一个简单的函数,将字符串中的字母进行大小写转换
#include <iostream>
#include <cctype> // 包含toupper和tolower函数
#include <string>
using namespace std;
// 一个简单的函数,将字符串中的字母进行大小写转换
string toggleCase(const string& str) {
string toggledStr;
for (char c : str) {
if (islower(c)) {
toggledStr.push_back(toupper(c)); // 小写转大写
} else if (isupper(c)) {
toggledStr.push_back(tolower(c)); // 大写转小写
} else {
toggledStr.push_back(c); // 保持不变
}
}
return toggledStr;
}
int main() {
string str = "Hello World!";
string toggledStr = toggleCase(str);
cout << toggledStr << endl;
return 0;
}