字符串转换大小写是一个常用的功能。
遗憾的是,std::string 没有提供大小写转换的功能。
有一种相对方便的方法是用STL中的transform结合toupper/tolower完成:
头文件: string, cctype,algorithm
转小写
transform(str.begin(),str.end(),str.begin(),tolower);
transform(wstr.begin(), wstr.end(), wstr.begin(), towlower);
转大写
transform(s.begin(), s.end(), s.begin(), toupper);
transform(wstr.begin(), wstr.end(), wstr.begin(), towupper);
Example:
wstring wstr =L"Abc";
transform(wstr.begin(), wstr.end(), wstr.begin(), towupper);
其实应该就是相当于自己写一个字符串的Tolower函数,通过不断调用cstdlib里面的tolower函数来实现:
#include "string"
#include "cstdlib"
void lower(std::string & str) {
for (int i = 0; i < str.size(); ++i)
str[i] = tolower(str[i]);
}
这种方法感觉比较蹩脚,相对于CPP其他方便的功能来讲是比较麻烦的。