M
Mike Copeland
What is a simple and reliable way to trim (remove leading and
trailing blanks) from a basic:string variable? TIA
trailing blanks) from a basic:string variable? TIA
(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");
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
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.