题目:
编写一个函数将字符反转,单词不反转,如:给出“I am a student”,反转后的结果应该是
“student a am I”.
解答:
#include <iostream>
#include <string>
#include <vector>
class MSStr
{
public:
MSStr( const std::string::const_iterator& _iter1,
const std::string::const_iterator& _iter2)
: iter1(_iter1),
iter2(_iter2)
{
}
MSStr(const MSStr& _str)
: iter1(_str.iter1),
iter2(_str.iter2)
{
}
MSStr& operator=(const MSStr& _str)
{
iter1 = _str.iter1;
iter2 = _str.iter2;
return *this;
}
std::string getStr() const
{
return std::string(iter1, iter2);
}
friend bool operator==(const MSStr& str1, const MSStr& str2);
friend bool operator!=(const MSStr& str1, const MSStr& str2);
private:
std::string::const_iterator iter1;
std::string::const_iterator iter2;
};
void parseStr(std::vector<MSStr>& vMSStr, const std::string& str);
std::string reverse(const std::vector<MSStr>& vMSStr);
int main(void)
{
std::string str;
std::cout << "input a string : " << std::endl;
std::getline(std::cin, str, '/n');
std::vector<MSStr> vMSStr;
parseStr(vMSStr, str);
std::cout << '<' << reverse(vMSStr) << '>' << std::endl;
return 0;
}
void parseStr(std::vector<MSStr>& vMSStr, const std::string& str)
{
if (str.empty())
{
return;
}
bool charToken = (str[0] != ' ');
std::string::const_iterator iter = str.begin();
std::string::const_iterator ci = str.begin();
for (; ci != str.end(); ++ci)
{
if (charToken && *ci == ' ')
{
charToken = false;
vMSStr.push_back(MSStr(iter, ci));
iter = ci;
}
else if (!charToken && *ci != ' ')
{
charToken = true;
vMSStr.push_back(MSStr(iter, ci));
iter = ci;
}
}
vMSStr.push_back(MSStr(iter, ci));
}
std::string reverse(const std::vector<MSStr>& vMSStr)
{
std::string ret;
for (std::vector<MSStr>::const_reverse_iterator ci = vMSStr.rbegin(); ci != vMSStr.rend(); ++ci)
{
ret += ci->getStr();
}
return ret;
}
inline bool operator==(const MSStr& str1, const MSStr& str2)
{
return (str1.iter1 == str2.iter1 && str1.iter2 == str2.iter2);
}
inline bool operator!=(const MSStr& str1, const MSStr& str2)
{
return !(str1 == str2);
}