給一個字串,有大小寫字母,要求寫一個函式把小寫字母放在前面 大寫字母放在後面,儘量使用最小空間,時間複雜度。(即用指標做)。 如:aAbBcCdD ---àabcdABCD
阿新 • • 發佈:2019-01-27
#include <stdlib.h>
int SmallToCaptial( char *str, char *outbuf )
{
char *p = str;
if (str == NULL || outbuf == NULL)
{
return -1;
}
while (*p)
{
if (*p >= 'a' && *p <= 'z')
{
*outbuf++ = *p; //小寫字母放在前面
}
p++;
}
p = str;
while (*p)
{
if (*p >= 'A' && *p <= 'Z')
{
*outbuf++ = *p; //找到大寫字母接在後面
}
p++;
}
*outbuf = '\0'; //加上結束標誌
return 0;
}
int main()
{
char *str = NULL; //含有大小寫字母的字串
char outbuf[100] = {0}; //存放處理好的字串
str = (char *)malloc(100 * sizeof(char));
printf ("please input a string (with capital letter and small letter):\n");
scanf ("%s", str);
printf ("The original string is %s\n", str);
if( SmallToCaptial(str, outbuf) == -1 )
{
printf ("function SmallToCaptial error!\n");
return -1;
}
printf ("The result is %s\n", outbuf);
free(str);
return 0;
}
int SmallToCaptial( char *str, char *outbuf )
{
char *p = str;
if (str == NULL || outbuf == NULL)
{
return -1;
}
while (*p)
{
if (*p >= 'a' && *p <= 'z')
{
*outbuf++ = *p; //小寫字母放在前面
}
p++;
}
p = str;
while (*p)
{
if (*p >= 'A' && *p <= 'Z')
{
*outbuf++ = *p; //找到大寫字母接在後面
}
p++;
}
*outbuf = '\0'; //加上結束標誌
return 0;
}
int main()
{
char *str = NULL; //含有大小寫字母的字串
char outbuf[100] = {0}; //存放處理好的字串
str = (char *)malloc(100 * sizeof(char));
printf ("please input a string (with capital letter and small letter):\n");
scanf ("%s", str);
printf ("The original string is %s\n", str);
if( SmallToCaptial(str, outbuf) == -1 )
{
printf ("function SmallToCaptial error!\n");
return -1;
}
printf ("The result is %s\n", outbuf);
free(str);
return 0;
}