(原創) 如何將std::string轉成大寫(小寫)? (C/C++) (STL) (C)

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);  
21 }

Reference
Danny Kalev, http://www.devx.com/getHelpOn/Article/9702/1954?pf=true , DevX
0
0
(请您对文章做出评价)
« 上一篇:(原創) 跨平台的GUI Framework : Qt (C/C++)
» 下一篇:(原創) 如何将图片左右翻转? (.NET) (ASP.NET) (C#) (GDI+) (Image Processing)

posted on 2006-10-15 14:22 真 OO无双 阅读(3175) 评论(5)  编辑 收藏 网摘 所属分类: STL, C, C/C++

评论

#1楼 2008-04-04 23:02 Kevink[未注册用户]

太感谢了!   回复  引用    

#2楼 2008-05-19 17:18 hanlu[未注册用户]

我用vc2005也像上面说的一样,为什么不行啊?   回复  引用    

#3楼[楼主] 2008-05-19 19:00 真 OO无双      

@hanlu
這我就不清楚了
我也是用VC8測的
  回复  引用  查看    

#4楼 2009-02-16 10:57 gamor[未注册用户]

thank you   回复  引用    

#5楼 2009-06-09 18:01 SkyKing[未注册用户]

C的例子寫錯了..
while(s[i++])
應該要改成以下才對, thanks!
while(s[++i])
  回复  引用    

导航

统计

公告

随笔分类(1938)

随笔档案(868)

最新评论