Wednesday, December 16, 2015

Remove a single character from std::string

This  might probably be one of the oldest tricks for 2015 for std::string but still blogging about it anyways.

To remove all instances of a single character from a std::string, you can use std::remove and string::erase.

#include // include for remove()

std::string str = "This is a test";
str.erase( std::remove( str.begin(), str.end(), 'e' ), str.end() );

This would remove the character e from string, and will provide result of "This is a tst"

If you want to remove quotes from the string,

std::string str = "This \" is a test \"";
str.erase( std::remove( str.begin(), str.end(), '\"' ), str.end() );

result str will have "This is a test" without the quotes. 

No comments: