您的位置:首页 > 其它

如何将英文句子中的单词位置倒置, 而不改变单词内部结构呢?

2018-01-25 22:13 351 查看
如何将英文句子中的单词位置倒置, 而不改变单词内部结呢?如“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;
}


8dc0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐