标准C、C++中字符串的大小写转换方法

   如何将一个字符串转换成大写或者小写?这是字符串匹配中经常需要做的事情,然而C++的Standard Library并没有提供将std::string转成大写和小写的功能,只有在提供将char转成大写(toupper)和小写(tolower)的功能而已。

    但我们可以利用STL的transform配合toupper/tolower,完成std::string转换大(小)写的功能,也看到模版编程的威力了,一个transform函数,可以适用于任何类型,且只要自己提供 函数 ,就可完成任何Transform的动作。

    以下介绍三种standard C、C++大小写转换方法。

    一、standard C method

#include <stdio.h>
#include <ctype.h>

int main()
{
 char s[]="This is a TEST string.";
 int i = -1;
 while(s[i++])
  s[i] = toupper(s[i]);
  //s[i] = tolower(s[i]);
  puts(s);

 return 0;
}

    二、standard C++ method
    2.1 调用toupper()/tolower()函数

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

using namespace std;

int main(void)
{
 string s="This is a TEST stinrg.";
 //original
 cout << "orig:" << s << endl;

 // to lower case
 transform(s.begin(),s.end(),s.begin(),::tolower);
 cout << "lower:" << s << endl;

 //to upper case
 transform(s.begin(),s.end(),s.begin(),::toupper);
 cout << "upper:" << s << endl;

 return 0;
}

    2.2 调用自己写的easytoupper()/easytolower()函数

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

using namespace std;

char easytolower(char in)
{
 if(in<='Z' && in>='A')
  return in-('Z'-'z');
 return in;
}

char easytoupper(char in)
{
 if(in<='Z' && in>='A')
  return in+('Z'-'z');
 return in;
}

int main(void)
{
 string s="This is a TEST stinrg.";
 //original
 cout << "orig:" << s << endl;

 // to lower case
 transform(s.begin(),s.end(),s.begin(),easytolower);
 cout << "lower:" << s << endl;

 //to upper case
 //transform(s.begin(),s.end(),s.begin(),easytoupper);
 //cout << "upper:" << s << endl;

 return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值