Tony is a cute student => tneduts etuc a si ynoT => student cute a is Tony
思路: 1>翻转整个字符串 2>再把单个单词进行翻转
#include <iostream>
#include <string.h>
using namespace std;
void reversalFunc(char * ch, int start, int end)
{
if (start >= end || end == 0)
{
return;
}
char temp = 0;
while(start < end)
{
temp = ch[start];
ch[start] = ch[end];
ch[end] = temp;
++start;
--end;
}
}
int main()
{
char ch[] = "Tony is a cute student";
//全部翻转
reversalFunc(ch, 0, strlen(ch) - 1);
//单词翻转
int start = 0;
for (int i = 0; i <= strlen(ch); i++)
{
if (ch[i] == ' ' || ch[i] == '\0')
{
reversalFunc(ch, start, i-1);
start = i + 1;
}
}
cout << ch << endl;
return 0;
}
最近学习了一下STL,刷题的时候又遇到了这个,写了下面这种
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string reverse(string sentence)
{
int start = 0, end = 0;
vector<string> vt;
string resultStr;
while (end <= sentence.size())
{
if (sentence[end] == ' ' || end == sentence.size())
{
vt.push_back(sentence.substr(start, end - start));
start = end + 1;
}
end++;
}
for (vector<string>::reverse_iterator it = vt.rbegin(); it != vt.rend(); ++it)
{
resultStr.append(*it);
resultStr.append(" ");
}
return resultStr;
}
int main()
{
string str;
getline(cin, str);
cout << reverse(str) << endl;
return 0;
}