zoukankan      html  css  js  c++  java
  • string类中字符的大小写转换

    今天做一道题,要用string类,涉及大小写转换,查看了C++文档,string类没有提供这样的方法,只好自己写。
    之后是想到一个比较笨的方法,我把string当成一个容器,然后用迭代器一个一个来替换。

    比如下面的是大写转小写:

    string temp;
    string::iterator it;
    for (it = temp.begin(); it != temp.end(); it++)
            if ((*it) < 'a')
                *it = *it + 32;

    测试一下代码:

    #include<iostream>
    #include<string>
    using namespace std;
    int main(void)
    {
        string temp;
        string::iterator it;
        cin >> temp;
        for (it = temp.begin(); it != temp.end(); it++) //大写转小写
            if ((*it) < 'a')
                *it = *it + 32;
        cout  <<"转换成小写之后" <<temp << endl;
        for (it = temp.begin(); it != temp.end(); it++) //小写转大写
            if ((*it) > 'Z')
                *it = *it - 32;
        cout  <<"转换成大写之后" <<temp << endl;
        return 0;
    }

    测试输入
    AsdFghJkL

    测试输出
    转换成小写之后asdfghjkl
    转换成大写之后ASDFGHJKL

    测试图片:

    但是后面我发现其他大佬有更简单的做法,使用模板函数transform可以轻松解决这个问题,我们只需要提供一个函数对象,例如将char转成大写的toupper函数或者小写的函数tolower函数。

    transform原型:

    template <class InputIterator, class OutputIterator, class UnaryOperator>
      OutputIterator transform (InputIterator first1, InputIterator last1,
                                OutputIterator result, UnaryOperator op)
    {
      while (first1 != last1) {
        *result = op(*first1);  // or: *result=binary_op(*first1,*first2++);
        ++result; ++first1;
      }
      return result;
    }

    以上的原型来自文档
    C++官方文档

    所以对于这个大小写转换只要这么写就行:

    transform(temp.begin(),temp.end(),temp.begin(),::tolower); //转小写
    transform(temp.begin(),temp.end(),temp.begin(),::toupper); //转大写

    更改代码

    #include<algorithm>
    #include<iostream>
    #include<string>
    using namespace std;
    int main(void)
    {
        string temp;
        cin >> temp;
        transform(temp.begin(),temp.end(),temp.begin(),::tolower); //转小写
        cout  <<"转换成小写之后" <<temp << endl;
        transform(temp.begin(),temp.end(),temp.begin(),::toupper); //转大写
        cout  <<"转换成大写之后" <<temp << endl;
        return 0;
    }

    结果一样:
    这里写图片描述

  • 相关阅读:
    java设计模式-代理模式
    java设计模式-适配器模式
    java设计模式-策略模式
    java设计模式-建造者模式
    HTML table 边框双线变单线
    flutter flutter_cupertino_date_picker 时间插件的用法
    flutter TextField 输入框被软键盘挡住的解决方案
    vue 多层组件相互嵌套的时候 数据源更新 dom没更新 彻底清除组件缓存
    elementUI 上传文件图片大小加了限制后 仍然上传了
    elementUI el-date-picker 时间范围设置 固定时间段可选 配置
  • 原文地址:https://www.cnblogs.com/FlyerBird/p/9052555.html
Copyright © 2011-2022 走看看