题解 | #单词倒排#
单词倒排
https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836
没看清楚限制每个单词最多22个,按单词任意长处理了。
先把非字母的换成空格,再定位每个最后空格位置输出最后一个单词,
将最后一个空格设为结束符0,可循环使用strrchr定位下一个最后单词。
#include <ctype.h>
#include <stdio.h>
int main()
{
char str1[10001];
char str[10001];
int k=0;
char *p, *tail;
fgets(str1, sizeof(str1), stdin);
for(int i=0; i<strlen(str1); i++)
{
if(isalpha(str1[i]))
str[k++] = str1[i];
else
{
str[k++] = ' ';
while(!isalpha(str1[++i]));
--i;
}
}
while(p=strrchr(str, ' '))
{
if(*(p+1))
printf("%s ", p+1);
*p = 0;
}
if(str[0])
printf("%s", str);
}

