在网上看到这样一个题目,如题
把字符串转换为小写,不成功返回NULL,成功返回新串
char* toLower(char* sSrcStr)
{
char* sDest= NULL;
if( __1___)
{
int j;
sLen = strlen(sSrcStr);
sDest = new [_______2_____];
if(*sDest == NULL)
return NULL;
sDest[sLen] = '\0';
while(_____3____)
sDest[sLen] = toLowerChar(sSrcStr[sLen]);
}
return sDest;
}
自己按那个题做了个填空.把上面的一些代码给改了,调试通过后如下
2 #include < stdio.h >
3 #include < iostream >
4
5 using namespace std;
6
7 char * toLower( char * sSrcStr)
8 {
9 char * sDest = NULL;
10
11 if ( * sSrcStr != ' 0 ' )
12 {
13 int j;
14 int sLen = strlen(sSrcStr);
15 sDest = new char [sLen];
16 if ( * sDest == NULL)
17 return NULL;
18 sDest[sLen] = ' \0 ' ;
19 while (sLen -- > 0 )
20 sDest[sLen] = ( char )(sSrcStr[sLen] + 32 ) ;
21 }
22
23 return sDest;
24
25 }
26
27
28 int main ( int argc, char * argv [])
29 {
30 char a[] = " HELLO " ;
31 cout << toLower(a);
32 }
33
但是总是觉得怪怪的
1. 13行那个int j ,都没有用到过
2. 15行new 了之后不要delete ? 这个和上面那个填空给出来的空不太一样,我改过了.不知道之前出这个题的人是想的是什么.
3. 20行是我为了调试通过,做了简化.其中没有考滤到空格,数字一类的转化.
{
int nLen = strlen(sSrcStr);
char * sDst = new char [nLen + 1 ];
memset(sDst, 0 , sizeof ( char ) * (nLen + 1 ));
char * sDstTemp = sDst;
char * temp = sSrcStr;
while ( * temp != ' \0 ' )
{
if (( * temp > ' A ' ) && ( * temp < ' Z ' ))
{
* temp += 32 ;
}
* sDstTemp ++ = * temp ++ ;
temp ++ ;
}
return sDst;
}
又改了一下
{
char * sDstTemp = sDstStr;
const char * temp = sSrcStr;
while ( * temp != ' \0 ' )
{
if (( * temp >= ' A ' ) && ( * temp <= ' Z ' ))
{
* sDstTemp ++ = ( * temp ++ ) + 32 ;
}
else
{
* sDstTemp ++ = * temp ++ ;
}
}
return sDstStr;
}
最下面这个方法,我们这样调用
int nLen = sizeof (str);
char * dstStr = new char [nLen];
memset(dstStr, 0 , sizeof ( char ) * (nLen));
cout << toLower(dstStr,srcStr);