用指定字符串(如%20)替换空格 时间复杂度为O(n)

#include <iostream>
#include <string>
using namespace std;
void ReplaceBlank(char* destr, const char* sostr, int sLen);

int main()
{
string sostr = "";
getline(cin, sostr);
int len = sostr.length();
int blanLen = 0;
for (int i=0; i<len; i++)
{
if (sostr[i] == ' ')
blanLen++;
}
const char* sstr = sostr.c_str();
char* destr = new char[2*blanLen + len + 1];
ReplaceBlank(destr,sstr, len+1);
cout<<destr<<endl;
delete [] destr;
return 0;
}

void ReplaceBlank(char* destr, const char* sostr, int sLen)
{
if ((destr != NULL) && (sostr != NULL))
{
int dindex = 0;
for (int sindex= 0; sindex<sLen; )
{
if (sostr[sindex] != ' ')
{
destr[dindex++] = sostr[sindex++];
}
else
{
destr[dindex++] = '%';
destr[dindex++] = '2';
destr[dindex++] = '0';
sindex++;
}
}
}
}

posted @ 2015-05-11 19:51  niupan369  阅读(288)  评论(0编辑  收藏  举报