怎么写可移植的字符转换程序
我们一般写小写字母转换成大写字母的句子是这样的
- C/C++ code
if('a' <= ch && ch <= 'z') ch = ch - 'a' + 'A';但是书上说,这样的写法不具有可移植性,在不采用ASCII的机器上就不行,那么该怎么写?比如,采用unicode的机器上怎么做?
[解决办法]
这本书说的是正确的。
只要使用标准库函数,就是可移植的。
判断用is_upper、is_lower,转换用upper、lower。
[解决办法]
我想它的意思就是说要用toupper吧?
7.4.2.2 The toupper function
Synopsis
1 #include <ctype.h>
int toupper(int c);
Description
2 The toupper function converts a lowercase letter to a corresponding uppercase letter.
Returns
3 If the argument is a character for which islower is true and there are one or more
corresponding characters, as specified by the current locale, for which isupper is true,
the toupper function returns one of the corresponding characters (always the same one
for any giv en locale); otherwise, the argument is returned unchanged.
[解决办法]
查MSDN是Windows程序员必须掌握的技能之一。
_strupr, _wcsupr, _mbsupr
Convert a string to uppercase.
char *_strupr( char *string );
wchar_t *_wcsupr( wchar_t *string );
unsigned char *_mbsupr( unsigned char *string );
Routine Required Header Compatibility
_strupr <string.h> Win 95, Win NT
_wcsupr <string.h> or <wchar.h> Win 95, Win NT
_mbsupr <mbstring.h> Win 95, Win NT
For additional compatibility information, see Compatibility in the Introduction.
Libraries
LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version
Return Value
These functions return a pointer to the altered string. Because the modification is done in place, the pointer returned is the same as the pointer passed as the input argument. No return value is reserved to indicate an error.
Parameter
string
String to capitalize
Remarks
The _strupr function converts, in place, each lowercase letter in string to uppercase. The conversion is determined by the LC_CTYPE category setting of the current locale. Other characters are not affected. For more information on LC_CTYPE, see setlocale.
_wcsupr and _mbsupr are wide-character and multibyte-character versions of _strupr. The argument and return value of _wcsupr are wide-character strings; those of _mbsupr are multibyte-character strings. These three functions behave identically otherwise.
Generic-Text Routine Mappings
TCHAR.H Routine _UNICODE & _MBCS Not Defined _MBCS Defined _UNICODE Defined
_tcsupr _strupr _mbsupr _wcsupr
Example
/* STRLWR.C: This program uses _strlwr and _strupr to create
* uppercase and lowercase copies of a mixed-case string.
*/
#include <string.h>
#include <stdio.h>
void main( void )
{
char string[100] = "The String to End All Strings!";
char *copy1, *copy2;
copy1 = _strlwr( _strdup( string ) );
copy2 = _strupr( _strdup( string ) );
printf( "Mixed: %s\n", string );
printf( "Lower: %s\n", copy1 );
printf( "Upper: %s\n", copy2 );
}
Output
Mixed: The String to End All Strings!
Lower: the string to end all strings!
Upper: THE STRING TO END ALL STRINGS!
Locale Routines | String Manipulation Routines
See Also _strlwr