关于string字符串的大小写转换

如何将一个string中的字符全部转换成大写或者全部转换成小写?C++标准目前并没有直接提供这种方法,但是我们可以通过STL的transform算法配合的toupper和tolower来实现该功能。

 STL的algorithm库确实给我们提供了这样的便利,开发人员只需要提供一个函数对象,即可实现大小写转换。

transform原型:

template < class InputIterator, class OutputIterator, class UnaryOperator >
  OutputIterator transform ( InputIterator first1, InputIterator last1,
                             OutputIterator result, UnaryOperator op );
 
template < class InputIterator1, class InputIterator2,
           class OutputIterator, class BinaryOperator >
  OutputIterator transform ( InputIterator1 first1, InputIterator1 last1,
                             InputIterator2 first2, OutputIterator result,
                             BinaryOperator binary_op );

测试代码:

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

using namespace std;

int main() 
{
    string src = "Hello World!";
    string dst;

    transform(src.begin(), src.end(), back_inserter(dst), ::toupper);
    cout << dst << endl;

    transform(src.begin(), src.end(), dst.begin(), ::tolower);
    cout << dst << endl;

    return 0;
 }

运行结果:

HELLO WORLD!
hello world!

赶紧去试一试吧。



参考文章:https://blog.csdn.net/loushuai/article/details/51289345

                https://blog.csdn.net/yasaken/article/details/7303903



猜你喜欢

转载自blog.csdn.net/Leo_csdn_/article/details/80974918