输入一个英文句子,翻转句子中单词的顺序。要求单词内字符的顺序不变,句子中单词以空格符隔开。为简单起见,标点符号和普通字母一样处理。例如,若输入“I am a student.”,则输出“student. a am I”
思路:
- 先找出每个单词,单词间都有空格隔开;
- 对每个单词进行字符翻转,如"abc"翻转为"cba";
- 单词翻转完后再对整体进行翻转就可以的到目标句子
#include <iostream>
using namespace std;
//倒序字符串指定位置
void ReverseString(char *s, int from, int to)
{
char t;
while (from < to) {
t = s[from];
s[from++] = s[to];
s[to--] = t;
}
}
//翻转英文句子
void ReverseSentence(char *s, int len)
{
int from = 0;
int to = 0;
int i = 0;
while (i++ <= len) {
if (s[to] == ' ' || s[to] == '\0') {
ReverseString(s, from, to - 1);//把每个单词倒序
from = ++to;//寻找下一个单词
}
else {
to++;
}
}
ReverseString(s, 0, len - 1);//整体翻转
}
int main()
{
int len;
char s[50];
cout << "请输入需要翻转的英文句子:" << endl;
cin.getline(s, sizeof(s));
len = strlen(s);
ReverseSentence(s, len);
cout << "翻转后的英文句子:" << endl;
cout << s << endl;
system("pause");
return 0;
}
注意:cin>>str和get函数都是遇到空格会截断,只返回空格前的字符串,用getline函数可实现字符串中含有空格的情况