1. 程式人生 > >將陣列倒置,單詞內部不變

將陣列倒置,單詞內部不變

  • “student a am i”--->"i am a student"
  • 思路:先把整個字串倒置,再利用空格將每個單詞倒置回來。
void reverse(char str[], int begin, int end)
{
	while (begin < end)
	{
		char temp = str[begin];
		str[begin] = str[end];
		str[end] = temp;
		begin++; end--;
	}
}

int main()
{
	int i = 0,j =0, length = 0;
	char str[] = "student a am i";
	while (str[length++]!='\0')
		;
	reverse(str, 0, length);//先把整個陣列倒置
	for (i = 0; i < length; i++)
	{
		if (str[i] == ' ')
		{
			reverse(str, j, i);//每個單詞倒置回來
			j = i + 1;
		}
	}
	for (i = 0; i < length; i++)//輸出陣列
	{
		printf("%c", str[i]);
	}
	system("pause");
	return 0;
}