Re: std::string::npos always < std::string::size() ?
On Jan 10, 4:52 am, "Christopher Pisz" <some...@somewhere.net> wrote:
Is std::string::npos always going to be less than any
std::string 's size()?
It's always going to be greater.
I am trying to handle a replacement of all occurances of a
substr, in which the replacement also contains the substr.
Yick. All I could come up with is:
#include <string>
int main()
{
std::string text;
text = "\nThis is a test line with newlines\n<-here and \n<-here and
\n\n<-two here";
// Format the text
std::string formattedText(text);
// Change every occurrance of "\n" to "\r\n"
std::string::size_type index = 0;
do
{
index = formattedText.find('\n', index);
if( index != std::string::npos )
{
formattedText.insert(index, "\r");
index += 2;
}
} while( index < formattedText.size() );
// debugging contents of formattedText here
return 0;
}
However, it depends on std::string::npos always being less
than the size of the string and I am not certain whether that
is safe or not.
Your code should work, although I'd definitely use a while or a
for, rather than a do...while:
for ( size_t pos = text.find( '\n' ) ;
pos != std::string::npos ;
pos = text.find( '\n', pos + 2 ) ) {
text.insert( pos, '\r' ) ;
}
But generally, I'd rather not do this sort of thing in place.
Something more like:
std::string
convertToDos( std::string const& source )
{
std::string result ;
for ( std::string::const_iterator it = source.begin() ;
it != source.end() ;
++ it ) {
switch (*it) {
case '\n' :
result += "\r\n" ;
break ;
default :
result += *it ;
break ;
}
}
return result ;
}
This seems a lot cleaner to me, despite having more lines of
code, and is probably faster as well (less copying). If the
strings are very long, and performance is still a problem, you
can add the following after the definition of result:
result.reserve( source.size()
+ std::count( source.begin(), source.end(),
'\n' ) ;
. Unless the strings are very long, however, it probably won't
matter.)
--
James Kanze (GABI Software) mailto:james.kanze@gmail.com
Conseils en informatique orient=EF=BF=BDe objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=EF=BF=BDmard, 78210 St.-Cyr-l'=EF=BF=BDcole, France, +33 (0)1 30 2=
3 00 34