题目:编写一个C函数,将”I am from shanghai ”倒置为”shanghai from am I”,即将句子中的单词位置倒置,而不改变单词内部结构.
#include <stdio.h>
int main()
{
char s[] = {"I am from shanghai"};
char str[100] = {0};
int i, j , k = 1,n = 0;
int len = strlen(s);
int tmp[4] ={0};
for(i = 0;i < len;i++)
{
if(s[i] == ' ')
{
tmp[k++] = i;
}
}
i = 0; k = 0;
while(1)
{
if(s[i] == ' '|| s[i] == '\0')
{
for(j = i-1;j >= tmp[k] ;j--)
{
str[n++] = s[j];
if(tmp[k] == 0)
{
str[n++] = ' ';
}
}
k++;
}
if(s[i] == '\0')
{
break;
}
i++;
}
for(i = len-1;i>=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
return 0;
}
#include <stdio.h>
int main()
{
char s[] = {"I am from shanghai"};
char str[100] = {0};
int i, j , k = 1,n = 0;
int len = strlen(s);
int tmp[4] ={0};
for(i = 0;i < len;i++)
{
if(s[i] == ' ')
{
tmp[k++] = i;
}
}
i = 0; k = 0;
while(1)
{
if(s[i] == ' '|| s[i] == '\0')
{
for(j = i-1;j >= tmp[k] ;j--)
{
str[n++] = s[j];
if(tmp[k] == 0)
{
str[n++] = ' ';
}
}
k++;
}
if(s[i] == '\0')
{
break;
}
i++;
}
for(i = len-1;i>=0;i--)
{
printf("%c",str[i]);
}
printf("\n");
return 0;
}