zoukankan      html  css  js  c++  java
  • string转化大小写(C++) | Vimer的程序世界

    string转化大小写(C++) | Vimer的程序世界

    string转化大小写(C++)

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

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

    C++

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    #include <iostream>
    #include <string>
    #include <cctype>
    #include <algorithm>
    using namespace std;
    int main() {
        string s = "Clare";
        // toUpper
        transform(s.begin(), s.end(), s.begin(), ::toupper);
        // toLower
        //transform(s.begin(),s.end(),s.begin(), ::tolower);
        cout << s << endl;
    }

    C

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    
    #include <stdio.h>
    #include <ctype.h>
    int main() {
        char s[] = "Clare";
        int i = -1;
        while(s[i++])
            s[i] = toupper(s[i]);
        // s[i] = tolower(s[i]);
        puts(s);
    }

    OK,代码就是这样啦。

  • 相关阅读:
    SQL
    第九章
    第三章 表单
    第二章 表格,列表,媒体元素
    HTML5基础
    Java第一本书总复习
    字符串
    人机猜拳
    类的无参方法
    类和对象
  • 原文地址:https://www.cnblogs.com/lexus/p/2598724.html
Copyright © 2011-2022 走看看