string: remove heading and trailing whitespaces
-
Hallo, gibt es eine C++ Standartfunktion, mit der ich von einem String alle vor- und nachgestellten whitespaces abschneiden kann?
ich möchte aus:
string lala(" \t lala \t\t ");
ein
string lala("lala");
machen. Meinetwegen darfs auch ne Funktion aus VisualC++ sein?
Besten Dank!
-
Hallo,
CString (die MFC-Klasse) hat Methoden namens TrimLeft und TrimRight.
boost::string_algo hat Funktionen namens trim_left und trim_right.Ansonsten musst du sowas selbst schreiben. Was unter Verwendung von string::find_first_not_of und string::erase ein Kinderspiel ist.
-
Die Boost-Lib ist sowieso pflicht.
-
void trim(std::string &s) { s.replace(0, s.find_first_not_of(" \t\n"), ""); s.replace(s.find_last_not_of(" \t\n") + 1, std::string::npos, ""); }
-
HumeSikkins schrieb:
string::find_first_not_of und string::erase ein Kinderspiel ist.
Danke, war einfach:
string.erase(0,string.find_first_not_of('\t')); string.erase(0,string.find_first_not_of(' '));
Die trailing whitespaces sind mir sowieso egal. Funktioniert jetzt zwar noch nicht bei " \t \t blabla" aber für mich reichts!
[Note]Wow, find_first_not_of() was'n underscoreder functionname![/Note]
-
0xdeadbeef schrieb:
void trim(std::string &s) { s.replace(0, s.find_first_not_of(" \t\n"), ""); s.replace(s.find_last_not_of(" \t\n") + 1, std::string::npos, ""); }
Das ist natürlich noch besser:
s.replace(0, s.find_first_not_of(" \t\n"), "");