实现一个函数reverse(char *),将指针所指向的字符串内的单词逆序输出,例如“Welcome to CppLive . com !”的指针传入该函数后输出“! com . CppLive to Welcome”。
问题的关键是先依靠空格符(‘ ‘)从字符串中划分出一个个单词出来,我们可以从字符串头循环读入一个个字符到一个临时string对象中,当遇到一个空格符时暂停读入,这时临时string对象中存储的便是一个单词,将该临时string对象push_back到一个vector中,同时clear该临时string对象以便重新存储下一个单词。当遇到null时,字符串便读入完毕,我们可以利用reverse_iterator从容器尾(rbegin())到容器头(rend())逆序输出。
/ * reverse_iterator_example.cpp * /
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void reverse(char *s)
{
char *tmp = s;
string tmpStr;
vector<string> words;
if (NULL == s) return;
while (*tmp)
{
if (*tmp != ' ')
{
tmpStr.insert(tmpStr.end(), *tmp);
}
else
{
if (!tmpStr.empty())
{
words.push_back(tmpStr);
tmpStr.clear();
}
}
tmp++;
}
if (!tmpStr.empty())
words.push_back(tmpStr);
for (vector<string>::reverse_iterator iter = words.rbegin(); iter != words.rend(); iter++)
cout << *iter << ' ';
cout << endl;
}
int main(void)
{
char text[100] = "Welcome to CppLive . com !";
reverse(text);
return 0;
}
运行结果:
! com . CppLive to Welcome
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。



