linux C++ string大小写转换

#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string s = "ddkfjsldjl";
    transform(s.begin(), s.end(), s.begin(), toupper);
    cout<<s<<endl;
    return 0;
}

    但在使用g++编译时会报错:
对 ‘transform(__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, <unresolved overloaded function type>)’ 的调用没有匹配的函数。
    这里出现错误的原因是Linux将toupper实现为一个宏而不是函数:
/usr/lib/syslinux/com32/include/ctype.h:

/* Note: this is decimal, not hex, to avoid accidental promotion to unsigned */
#define _toupper(__c) ((__c) & ~32)
#define _tolower(__c) ((__c) | 32)

__ctype_inline int toupper(int __c)
{
return islower(__c) ? _toupper(__c) : __c;
}

__ctype_inline int tolower(int __c)
{
return isupper(__c) ? _tolower(__c) : __c;
}

    两种解决方案:

1.transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);

    这里(int (*)(int))toupper是将toupper转换为一个返回值为int,参数只有一个int的函数指针。

2.自己实现ToUpper函数:
int ToUpper(int c)
{
    return toupper(c);
}
transform(str.begin(), str.end(), str.begin(), ToUpper);

附:大小写转换函数
#include <cctype>
#include <string>
#include <algorithm>

using namespace std;

void ToUpperString(string &str)
{
    transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);
}

void ToLowerString(string &str)
{
    transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值