//写一个函数,实现字符串内单词逆序
//比如student a am i。逆序后i am a student。
#include <stdio.h>
#include <string.h>
#include <assert.h>
void reverse_string(char *left, char *right) //连续的字符串逆序
{
char temp;
while (right > left)
{
temp = *left;
*left = *right;
*right = temp;
left++;
right--;
}
}
char *reserve(char *str)
{
assert(str);
char *first = str;
char *last = str + strlen(str) - 1;
while (*str)
{
char *part = str;
while (*str != ' '&&*str != '\0')
{
str++;
}
reverse_string(part, str - 1);
if (*str != '\0')
{
str++;
}
else
break;
}
reverse_string(first, last);
return first;
}
int main()
{
char p[] = "student a am i";
printf("%s\n", reserve(p));
return 0;
}
|
请发表评论