Trim basic;;string

M

Mike Copeland

What is a simple and reliable way to trim (remove leading and
trailing blanks) from a basic:string variable? TIA
 
V

Victor Bazarov

(e-mail address removed) (Mike Copeland) wrote in @news.eternal-september.org:


You mean only blanks, or also tabs, linefeeds, etc? Vertical tab, form-
feed? Wide space, thin space, zero-width space, en quad, em quad? Unicode
non-breaking space characters (U+00A0, U+202F, U+2060?). Mongolian Vowel
Separator? Etc, etc.

An example for the case when the set of "whitespace" characters is fixed
and not locale dependent:

std::string Trim(const std::string& src) {
typedef std::string::size_type strpos_t;
strpos_t startpos = src.find_first_not_of(" \t\r\n\v\f");
if (startpos==src.npos) {
return std::string();
} else {
strpos_t endpos = src.find_last_not_of(" \t\r\n\v\f");

This comment is tangential, sorry to barge in. It's basically BTW
without any subject matter...

For code maintenance it would be desirable to define that string in
quotes only once in the program than repeat it. If a change needs to be
made, it's easier to make it once. Same goes for naming that constant
to explain its meaning, and adding a comment next to its definition if
needed.

To OP: pull the string literal out of the immediate code and declare a
const char array and initialise it with that string literal right where
you declare/define it. Name it appropriately. Use that array in both
'find_first_not_of' and 'find_last_not_of' calls.
return src.substr(startpos, endpos-startpos+1);
}
}

If you want locale-specific whitespace detection, then you need to
utilize std::isspace() instead somehow.

Generalization to any std::basic_string template class left as an
exercise.

hth
Paavo

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,266
Latest member
DavidaAlla

Latest Threads

Top