#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
/*
问题:编写一个方法,将字符串中的空格全部替换为“%20”。
假定该字符串尾部留有足够的控件存放新增字符,并且知道字符串的真实长度
分析:先扫描字符串,计算出空格总数n,字符串长度L,由于一个空格和“%20”相差两个字符,
因此替换后的字符串总长度为=L + 2n
然后将原字符串依次从后向前拷贝至新子串对应位置
输入:
chao ma yan ma
输出
chao%20ma%20yan%ma
关键:
1 先扫描字符串,计算出空格总数n,字符串长度L,由于一个空格和“%20”相差两个字符,
因此替换后的字符串总长度为=L + 2n
然后将原字符串依次从后向前拷贝至新子串对应位置
2 需要支持带空格的字符串,使用getline(cin , str)
*/
string stringReplace(string& str , const char findStr , const string& replaceStr)
{
int pos = 0;
int iCount = 0;
//如果找到该字符串
while( string::npos != str.find(findStr , pos))
{
iCount++;
pos = str.find(findStr , pos) + 1;
}
int totalLength = str.length() + 2 * iCount;
int i = totalLength - 1;
int j = str.length() - 1;
vector<char> str2(totalLength , 'a');
for( ; j >= 0 ; )
{
//如果不是待查找字符
if(str[j] != findStr)
{
//这边长度还没有开启
str2[i--] = str[j--];
}
//如果是待查找字符,则令当前为“0”
else
{
str2[i--] = '0';
str2[i--] = '2';
str2[i--] = '%';
j--;
}
}
string sResult = "";
vector<char>::iterator it = str2.begin();
for( ; it != str2.end() ; it++ )
{
sResult += *it;
}
return sResult;
}
int main(int argc, char* argv[])
{
string str;
//需要支持带空格的字符串
while( getline(cin , str))
{
char findStr = ' ';
string replaceStr = "%20";
string result = stringReplace(str , findStr , replaceStr);
cout << result << endl;
}
system("pause");
return 0;
}