【C语言】写一个函数,实现字符串内单词逆序

//写一个函数,实现字符串内单词逆序
//例如student a am i,逆序后i am a student。
#include 
#include 
#include 
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;
}

你可能感兴趣的:(【C语言】写一个函数,实现字符串内单词逆序)