2011-03-22 wcdj
问题描述:
i wanna to make a prog which convert small case letters entered by user to upper case letters....i TRIED to use toupper function ...but it only do action with a single character...is there any function which convert all characters like "lovely hakeem" to "LOVELY HAKEEM"
(NOT BY LOOP)
There is no way to convert all characters to upper or lower case without looping through the string.
下面总结几种常用的大写转小写的方法
方法1:逐个字符判断,是大写字母+32
#include <cstdio> #include <cstring> int main() { char str[128]; gets(str); for (int i = 0; i < strlen(str); i++) if (str[i] >= 'A' && str[i] <= 'Z') str[i] += 32; printf("%s/n", str); return 0; }
方法2:使用标准库算法transform
#include<string> #include<algorithm> #include<iostream> using namespace std; int main() { string str; cin>>str; transform(str.begin(),str.end(),str.begin(),tolower); cout<<str; return 0; }
方法3:使用ctype中的函数
/* TOUPPER.C: This program uses toupper and tolower to * analyze all characters between 0x0 and 0x7F. It also * applies _toupper and _tolower to any code in this * range for which these functions make sense. */ #include <conio.h> #include <ctype.h> #include <string.h> char msg[] = "Some of THESE letters are Capitals/r/n"; char *p; void main( void ) { _cputs( msg ); /* Reverse case of message. */ for( p = msg; p < msg + strlen( msg ); p++ ) { if( islower( *p ) ) _putch( _toupper( *p ) ); else if( isupper( *p ) ) _putch( _tolower( *p ) ); else _putch( *p ); } } Output Some of THESE letters are Capitals sOME OF these LETTERS ARE cAPITALS
方法4:使用string中的函数 (NOT ANSI standard)
#include <string.h > #include <stdio.h > int main( void ) { char string[100] = "The String to End All Strings!"; printf( "Mixed: %s/n", string ); _strlwr(string);// C库函数变小写 printf( "Lower: %s/n", string); _strupr(string);// C库函数变大写 printf( "Upper: %s/n", string); }
PS: A foreigner's method
// You can do your own easily enough: // C #include <ctype.h> char* stoupper( char* s ) { char* p = s; while (*p = toupper( *p )) p++; return s; } // C++ #include <algorithm> #include <cctype> #include <functional> std::string& stoupper( const std::string& s ) { std::string result( s ); std::transform( s.begin(), s.end(), result.begin(), std::ptr_fun <int, int> ( std::toupper ) ); return result; } //Etc. Hope this helps.
更多内容参考:
http://www.cplusplus.com/forum/general/33439/
http://www.cplusplus.com/forum/beginner/14081/
http://topic.csdn.net/u/20071015/21/4c266542-c3a6-4a5a-9754-fc7574ca5ef6.html