题目
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串“I am a student.”,则输出"student. a am I"。
方法一
使用是stream中的istringstream绑定输入的字符串,依次读取每个单词,并将该单词存储在栈中,待单词读取完,从栈顶依次取出元素即可。
源码:
#include<iostream>
#include<sstream>
#include<stack>
using namespace std;
void ReverseStr(string str)
{
if (str.empty())
{
cout << "输入的字符串为空,无需翻转" << endl;
return;
}
istringstream sst(str);
string temp;
stack<string> stk;
while (sst >> temp)
stk.push(temp);
while (!stk.empty())
{
cout << stk.top() << " ";
stk.pop();
}
}
void test1()
{
cout << "==============test1:nullptr==============" << endl;
string str;
ReverseStr(str);
cout << endl;
}
void test2()
{
cout << "==============test1:I am a student.==============" << endl;
string str = "I am a student.";
ReverseStr(str);
cout << endl;
}
int main()
{
test1();
test2();
system("pause");
return 0;
}
运行结果:
==============test1:nullptr==============
输入的字符串为空,无需翻转
==============test1:I am a student.==============
student. a am I
请按任意键继续. . .
方法二
分析
第一步先翻转句子中所有的字符,第二步翻转每个单词中的字符。
源码
#include<iostream>
using namespace std;
void Reverse(char *arr, int length)
{
if (arr == nullptr || length <= 1)
return;
char *pBegin = arr;
char *pEnd = arr + length - 1;
while (pBegin < pEnd)
{
char temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
++pBegin;
--pEnd;
}
}
void ReverseSentense(char *arr, int length)
{
if (arr == nullptr || length <= 1)
{
cout << "无需翻转" << endl;
return;
}
//翻转整个句子
Reverse(arr, length);
//翻转每个单词
char *pBegin = arr;//指向每个单词的第一个字符
char *pEnd = arr;//指向每个单词的最后一个字符
while (*pBegin != '\0')
{
if (*pBegin == ' ')
{
++pBegin;
++pEnd;
}
else if (*pEnd == ' ' || *pEnd == '\0')
{
Reverse(pBegin, pEnd - pBegin);
pBegin = pEnd++;
}
else
++pEnd;
}
}
void test11()
{
cout << "==============test1:nullptr==============" << endl;
char *str = nullptr;
ReverseSentense(str, 0);
cout << endl;
}
void test12()
{
cout << "==============test1:I am a student.==============" << endl;
char str[] = "I am a student.";
ReverseSentense(str, strlen(str));
cout << str << endl;
}
void test13()
{
cout << "==============test1:Apple.==============" << endl;
char str[] = "Apple.";
ReverseSentense(str, strlen(str));
cout << str << endl;
}
void test14()
{
cout << "==============test1:\" \"==============" << endl;
char str[] = " ";
ReverseSentense(str, strlen(str));
cout << str << endl;
}
int main()
{
test11();
test12();
test13();
test14();
system("pause");
return 0;
}
==============test1:nullptr==============
无需翻转
==============test1:I am a student.==============
student. a am I
==============test1:Apple.==============
Apple.
==============test1:" "==============
请按任意键继续. . .