如何将英文句子中的单词位置倒置, 而不改变单词内部结呢?如“I am from China”倒置为“China from am I”
我的思路是用一个数组记录这句话中每一个空格后的第一个字符的下标,从最后一个空格开始记录 ,然后按照记录的顺序打印,最后添加打印剩余的第一个没有被记入下标数组的字符串。
#include <iostream>
using namespace std;
void func1(char *str)
{
int blank_count = 0;
int j = 0;
for(unsigned int i = 0; i <= (strlen(str) - 1); i++)
{
if(str[i] == ' ')
blank_count++;
}
int *blank_index = new int[blank_count];
for(int i = strlen(str) - 1; i >= 0; i--)
{
if(str[i] == ' ')
blank_index[j++] = i + 1;
}
for(j = 0; j < blank_count; j++)
{
while(str[blank_index[j]] != ' ' && str[blank_index[j]] != '\0')
cout<<str[blank_index[j]++];
cout<<" ";
}
int i = 0;
while(str[i] != ' ' )
cout<<str[i++];
delete blank_index;
blank_index = NULL;
cout << endl;
}
int main()
{
char *str = "I am from China";
func1(str);
return 0;
}