一道面试题

来源:互联网 发布:商业会计的软件 编辑:程序博客网 时间:2024/05/22 00:43

编写一个方法,将字符串中的空格全部替换为“%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;
}

0 0
原创粉丝点击