复杂交换字符串

有一个字符数组的内容为:“student a am i”,
请你将数组的内容改为"i am a student".
要求:
不能使用库函数。
只能开辟有限个空间(空间个数和字符串的长度无关)。

student a am i
i ma a tneduts
i am a student

#include <stdio.h>
#include <stdlib.h>
void main()
{
	char str[] = "student a am i";
	printf(str);
	printf("\n");
	char *p, *q;
	char temp;
	p = q = str;
	while (*q != '\0')
	{
		q++;
	}
	q--;
	while (p <= q)
	{
		temp = *p;
		*p = *q;
		*q = temp;
		p++;
		q--;
	}//反转整个字符串

	printf(str);
	printf("\n");

	char *s;
	q = p = s = str;//指针指向开始位置
	while (*q != '\0')
	{
		if (*q == ' ' || *(q + 1) == '\0')
		{
			p--;
			if (*(q + 1) == '\0')//处理最后一个字串
				p++;
			while (s <= p)
			{
				temp = *p;
				*p = *s;
				*s = temp;
				s++;
				p--;
			}//反转局部字符串

			s = q + 1;
			p = q;
		}
		q++;
		p++;
	}

	printf(str);
	system("pause");
	printf("\n");
}

猜你喜欢

转载自blog.csdn.net/Lange_Taylor/article/details/89037022