如何将一个字符串转换成大写或者小写?这是字符串匹配中经常需要做的事情。然而C++的Standard Library并没有提供将std::string转成大写和小写的功能,只有在<cctype>中提供了将char转成大写(toupper)和小写(tolower)的函数而已。 但我们可以利用STL的transform配合toupper/tolower,完成std::string转换大(小)写的功能。一个transform函数,可以适用于任何类型,且只要自己提供操作函数,就可完成任何想要的动作。
C++#include <iostream>#include <string>#include <cctype>//toupper/tolower#include <algorithm>//transformusing namespace std;int main() {
C#include <stdio.h>#include <ctype.h>//toupper/tolowerint main() {
在linux下编译的时候会遇到以下报错:
对‘transform(std::basic_string<char>::iterator,std::basic_string<char>::iterator,std::basic_string<char>::iterator, <未解决的重载函数类型>)’的调用没有匹配的函数
问题提示没找到匹配的操作函数,解决方法是在tolower/toupper前加上::
transform(s.begin(), s.end(), s.begin(), ::toupper);
新闻热点
疑难解答
图片精选