您的位置:首页 > 其它

把std::string 转换大小写

2011-06-07 16:02 232 查看
Abstract

C++的Standard Library並沒有提供將std::string轉成大寫和小寫的功能,只有在<cctype>提供將char轉成大寫(toupper)和小寫(tolower)的功能而已,在此利用STL的transform配合toupper/tolower,完成std::string轉換大(小)寫的功能,也看到Generics的威力,一個transform function,可以適用於任何型別,且只要自己提供Algorithm,就可完成任何Transform的動作。

C++



1 /*

2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3

4 Filename : StringToUpper.cpp

5 Compiler : Visual C++ 8.0

6 Description : Demo how to upper string in C++

7 Release : 04/03/2008 1.0

8 */

9 #include <iostream>

10 #include <string>

11 #include <cctype>

12 #include <algorithm>

13

14 using namespace std;

15

16 int main() {

17 string s = "Clare";

18 // toUpper

19 transform(s.begin(), s.end(), s.begin(), toupper);

20

21 // toLower

22 //transform(s.begin(),s.end(),s.begin(),tolower);

23

24 cout << s << endl;

25 }

C語言


1 /*

2 (C) OOMusou 2008 http://oomusou.cnblogs.com
3

4 Filename : toupper.c

5 Compiler : Visual C++ 8.0

6 Description : Demo how to upper string in C

7 Release : 04/03/2008 1.0

8 */

9 #include <stdio.h>

10 #include <ctype.h>

11

12 int main() {

13 char s[] = "Clare";

14 int i = -1;

15

16 while(s[i++])

17 s[i] = toupper(s[i]);

18 // s[i] = tolower(s[i]);

19

20 puts(s);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐