编写程序颠倒句子中单词的顺序,该如何解决
编写程序颠倒句子中单词的顺序
Enter a sentece: you can cage a swallow can't you? (下划线为用户输入的字符)
Reversal of sentence: you can't swallow a cage can you?
提示:用循环逐个读取字符,然后将他们储存在一个一维字符数组中。当遇到句话、问号或者感叹号(成为“终止字符”)时,终止循环并把终止字符存储在一个char类型的变量中。然后再用一个循环反向搜索数组,找到最后一个单词的起始位置。显示最后一个单词,然后反向搜索倒数第二个单词。重复这一过程,直至到达数组的起始位置。最后显示出终止字符。
------解决思路----------------------
算法基本上也给出来了
思路都有了
楼主可以自己动手编码的
------解决思路----------------------
执行结果:
Enter a sentence
How are you? I am fine.What Can I do for you?No thanks.
you are How?
fine am I .
you for do I Can What?
thanks No.
请按任意键继续. . .
Enter a sentece: you can cage a swallow can't you? (下划线为用户输入的字符)
Reversal of sentence: you can't swallow a cage can you?
提示:用循环逐个读取字符,然后将他们储存在一个一维字符数组中。当遇到句话、问号或者感叹号(成为“终止字符”)时,终止循环并把终止字符存储在一个char类型的变量中。然后再用一个循环反向搜索数组,找到最后一个单词的起始位置。显示最后一个单词,然后反向搜索倒数第二个单词。重复这一过程,直至到达数组的起始位置。最后显示出终止字符。
------解决思路----------------------
算法基本上也给出来了
思路都有了
楼主可以自己动手编码的
------解决思路----------------------
void reserverSentence(const char* sentence, int len, char sep)
{
int *index_mark = new int[len]();
int word_num = 1;
index_mark[0] = -1;
for(int i = 0; i < len; i++)
{
if(sentence[i] == ' ')
{
index_mark[word_num] = i;
word_num++;
}
}
char * word;
int word_start, word_len;
index_mark[word_num] = len;
word_num++;
for(int i = word_num - 1; i > 0; i--)
{
word_start = index_mark[i - 1] + 1;
word_len = index_mark[i] - word_start;
word = new char[word_len + 1]();
memcpy(word, sentence + word_start, word_len);
cout<<word;
if(i != 1)
{
cout<<" ";
}
delete[] word;
}
cout<<sep<<endl;
delete[] index_mark;
}
void reserverSentences(const char* sentences, int len)
{
int old_pos = -1;
for(int i = 0; i < len; i++)
{
if(sentences[i] == '.'
------解决思路----------------------
sentences[i] == '?'
------解决思路----------------------
sentences[i] == '!')
{
reserverSentence(sentences + old_pos + 1, i - old_pos - 1, sentences[i]);
old_pos = i;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"Enter a sentence"<<endl;
string line;
getline(cin, line);
reserverSentences(line.c_str(), line.size());
system("pause");
return 0;
}
执行结果:
Enter a sentence
How are you? I am fine.What Can I do for you?No thanks.
you are How?
fine am I .
you for do I Can What?
thanks No.
请按任意键继续. . .