Re: string replacing
Alexander Cherny wrote:
creating a function, that would change any non-ASCII-7 character to a
"ϧ" value and any whitespace to a space, i got this one:
const string encodeXML(const string &S)
{
string s(S);
// convert the second half of the ASCII table
for(size_t i = 0; i < s.length(); ++i)
if((unsigned char)s[i] > (unsigned char)127) {
// replace the character by ϧ
string byrep("&#"+U::ltoa((unsigned char)s[i])+";");
s.replace(i, 1, byrep);
i += byrep.length()-1;
} else if((unsigned char)s[i] < (unsigned char)32)
s[i] = ' ';
return s;
}
i suspect this is not a most effective solution.
Don't guess, profile. Seriously, there is nothing else to say about this
topic before you profiled.
each time replace() called the string reallocation may happen.
Right.
is it possible to make it better?
Well, first thing I would do is remove all C-style casts. Those only serve
to confuse readers and cause errors. Then, I would write a function that
takes a single char and returns the char or the replacement for it. Then,
but that almost follows the second step, I wouldn't first copy the string
but rather transform the source string char by char and append it to the
target string. KISS principle.
BTW: XML doesn't allow everything as content, in particular not everything
in the range 127-255. Further, 127 is also not a valid ASCII char, the last
one is 126.
Uli