toupper函数 与 tolower 函数(可用于洛谷第5704题字母转换)c++大小写字母转换

toupper函数

在 C++ 中,toupper 函数用于将小写字母转换为大写字母。这个函数在<cctype> 头文件中定义,属于 C++ 的 ctype 库。toupper 函数有两种用法:

  1. 作为函数模板使用,接受一个字符作为参数,并返回该字符的大写形式(如果它是小写字母)。
#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值