“student a am i”的倒置

前端之家收集整理的这篇文章主要介绍了“student a am i”的倒置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

问题:如何实现student a am i转换成为i am a student?

解析:可将语句完全倒置,成为i ma a tneduts,再将逐个单词倒置,成为i am a student

#include <stdio.h>
#include <string.h>

void reverse_string(char *l,char *r)
{
	while (l < r)
	{
		char tmp = *l;
		*l = *r;
		*r = tmp;
		l++;
		r--;
	}
}
void reverse(char ch[],int len)
{
	int i = 0;
	char *ctmpl = ch;
	char *ctmpr = ch;
	while (ch[i])
	{
		if (ch[i] == ' ')
		{
			reverse_string(ctmpl,ctmpr-1);
			ctmpl = ++ctmpr;
		}
		else
		{
			ctmpr++;
		}
		i++;
	}
	reverse_string(ch,ch + len - 1);
}
int main()
{
	char ch[] = "student a am i";
	reverse(ch,strlen(ch));
	printf("%s\n",ch);
}

猜你在找的设计模式相关文章