题解 | #句子逆序#
句子逆序
http://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3
解法一
#include <string.h>
int main(void)
{
char str[1000] = {0};
int len;
fgets(str, 1001, stdin);
len = (int) strlen(str); //fgets读取的字符串末尾:\n\0
for (int i = len - 1; i >= 0; --i)
{
if (str[i] == ' ')
{
for (int j = i + 1; j < len; ++j)
{
if (str[j] != ' ' && str[j] != '\n')
printf("%c", str[j]);
else
break;
}
printf(" ");
}
else if (i == 0)
{
for (int k = 0; k < len; ++k)
{
if (str[k] != ' ' && str[k] != '\n')
printf("%c", str[k]);
else
break;
}
}
else
continue;
}
return 0;
}
解法二
#include <string.h>
int main(void)
{
char str[1000] = {0};
int len;
fgets(str, 1001, stdin);
len = (int) strlen(str); //fgets读取的字符串末尾:\n\0
for (int i = len - 1; i >= 0; --i)
{
if (str[i] == ' ')
{
for (int j = i + 1; j < len; ++j)
{
if (str[j] != ' ' && str[j] != '\n')
printf("%c", str[j]);
else
break;
}
str[i + 1] = '\0';
printf(" ");
}
/*
else if (i == 0)
{
for (int k = 0; k < len; ++k)
{
if (str[k] != ' ' && str[k] != '\n')
printf("%c", str[k]);
else
break;
}
}
*/
else
continue;
}
printf("%s", str);
return 0;
}