B
baobaoba
Hi, I have a piece of code to do string replacement :
#include <iostream>
#include <string>
using namespace std;
void charEscape (string& src)
{
const string delims("&<");
string::size_type begIndex, endIndex;
begIndex = src.find_first_of(delims);
while (begIndex != string::npos)
{
if (src[begIndex] == '&')
{
src.replace(begIndex,begIndex, "&");
begIndex += 5;
}
else if (src[begIndex] == '<')
{
src.replace(begIndex,begIndex, "<");
begIndex += 4;
}
cout <<src <<endl;
begIndex = src.find_first_of(delims, begIndex);
}
}
int main ()
{
string charCont = "a&b<c";
int cap = charCont.capacity();
int size = charCont.size();
cout << "capacity: "<<cap << " " <<"size: " <<size <<endl;
charEscape (charCont);
cout << charCont <<endl;
cap = charCont.capacity();
size = charCont.size();
cout << "capacity: "<<cap << " " <<"size: " <<size <<endl;
}
I want to replace "&" with "&" and "<" with "<". What I got finally
is "a&b<". 'c' was lost. I test this on VC++6 and g++3x with the
same result. Can anybody point out what I did wrong ?
thanks
#include <iostream>
#include <string>
using namespace std;
void charEscape (string& src)
{
const string delims("&<");
string::size_type begIndex, endIndex;
begIndex = src.find_first_of(delims);
while (begIndex != string::npos)
{
if (src[begIndex] == '&')
{
src.replace(begIndex,begIndex, "&");
begIndex += 5;
}
else if (src[begIndex] == '<')
{
src.replace(begIndex,begIndex, "<");
begIndex += 4;
}
cout <<src <<endl;
begIndex = src.find_first_of(delims, begIndex);
}
}
int main ()
{
string charCont = "a&b<c";
int cap = charCont.capacity();
int size = charCont.size();
cout << "capacity: "<<cap << " " <<"size: " <<size <<endl;
charEscape (charCont);
cout << charCont <<endl;
cap = charCont.capacity();
size = charCont.size();
cout << "capacity: "<<cap << " " <<"size: " <<size <<endl;
}
I want to replace "&" with "&" and "<" with "<". What I got finally
is "a&b<". 'c' was lost. I test this on VC++6 and g++3x with the
same result. Can anybody point out what I did wrong ?
thanks