Re: std::string find_first_of and replace
On Wed, 9 Jul 2014 18:47:33 CST
Christopher Pisz <nospam@notanaddress.com> wrote:
bool Transform_DatetimeString(const std::string & fromXml,
std::string & toSql)
{
toSql = fromXml;
std::string::size_type pos = std::string::npos;
while( pos = toSql.find_first_of('/') != std::string::npos )
{
toSql = toSql.replace(pos, 1, '-', 1);
}
return true;
}
Wouldn't you prefer
replace_if( toSql.begin(), toSql.end(),
bind1st(equal_to<char>(), '/'), '-' );
Then you might have a much simpler function:
string toSqlDatetime( const string& input )
{
string output(input);
replace_if( output.begin(), output.end(),
bind1st(equal_to<char>(), '/'), '-' );
return output;
}
I think you thought you were using
string&
replace (size_t pos, size_t len, const char* s, size_t n);
but because you passed a character and not a character pointer,
you got
string&
replace (size_t pos, size_t len, size_t n, char c);
meaning, because '-' is ASCII 45
toSql = toSql.replace(pos, 1, '-', 1);
replaces position 0 with 45 elements of character 1.
By using the std algorithms, you stay on the fairway and write less
code. :-)
--jkl
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]