您的位置:首页 > 职场人生

一道面试题

2015-09-07 12:45 302 查看
编写一个方法,将字符串中的空格全部替换为“%20”,假设字符串有足够的空间新增字符,并且知道字符串的真实长度;

输入:“Mr John Smith”

输出: "Mr%20John%20Smith"

#include<string>

#include<iostream>

#include<memory>

#include<algorithm>

using std::endl;

using std::cin;

using std::cout;

using std::tr1::shared_ptr;

typedef std::string::iterator iterStr;

typedef struct{

iterStr pBegin;

iterStr pEnd;

}chk;

void changeString(std::string& str, const shared_ptr<chk>& pChk)

{

iterStr pBegin = pChk->pBegin;

iterStr pEnd = pChk->pEnd;

str.erase(pBegin, pEnd);

std::string curStr = { "%20" };

str.insert(pBegin, curStr.cbegin(), curStr.cend());

}

void changeAll(std::string& str)

{

int countRef = 0;

std::tr1::shared_ptr<chk> Chk = std::make_shared<chk>();

iterStr pBegin = str.begin();

while (pBegin != str.cend()){

if (*pBegin == ' ')

{

++countRef;

if (countRef == 1)

{

Chk->pBegin = pBegin;

}

else if (countRef == 2)

{

countRef = 0;

Chk->pEnd = pBegin+1;

changeString(str, Chk);

}

}

++pBegin;

}

if (countRef == 1 && pBegin == str.end())

{

Chk->pEnd = pBegin;

changeString(str, Chk);

}

}

int main()

{

std::string str = { " I am a People" };

changeAll(str);

/*

std::string str1 = { "%20" };

std::tr1::shared_ptr<chk> pChk = std::make_shared<chk>();

pChk->pBegin = str.begin()+1;

pChk->pEnd = str.begin()+3;

changeString(str, pChk);

*/

cout << str << endl;

int x;

cin >> x;

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: