String中改变大小写系列函数的用法

1.c语言中的tolower() (变小写) toupper() (变大写)

(1)函数定义的类型为char,因此用string的话要遍历string里面的每个值

(2)使用样例:

{1}#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s = "ABCDEFG";
    for( int i = 0; i < s.size(); i++ )
    {
        s[i] = tolower(s[i]);
    }
    cout<<s<<endl;
    return 0;
}
结果为abcdefg
{2}
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s = "abcdefg";
    for( int i = 0; i < s.size(); i++ )
    {
        s[i] = toupper(s[i]);
    }
    cout<<s<<endl;
    return 0;
}
结果为ABCDEFG
2.通过STL的transform算法配合的toupper和tolower来实现该功能就不需要用s[i]的方法
(1)函数的定义类型为char,因为要从string.begin()遍历到 string.end()
(2)使用样例:
{1}#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string s = "ABCDEFG";
    string result;
    transform(s.begin(),s.end(),s.begin(),::tolower);
    cout<<s<<endl;
    return 0;
}
结果:abcdefg
{2}#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string s = "abcdefg";
    string result;
    transform(s.begin(),s.end(),s.begin(),::toupper);
    cout<<s<<endl;
    return 0;
}
结果:ABCDEFG
3.判断是否为大小写isupper()和islower()
(1)定义类型为char,若与判断的相同则返回1,若不同返回0.
(2)使用样例:
 {1}cout << islower('a');//输出1
 cout << islower('A');//输出0
{2}cout << isupper('a');//输出0
 cout << isupper('A');//输出1
posted @ 2019-04-05 14:52  Tankawa  阅读(2291)  评论(0编辑  收藏  举报