howto:trim_string
Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen angezeigt.
— | howto:trim_string [2020-07-27 09:37] (aktuell) – angelegt - Externe Bearbeitung 127.0.0.1 | ||
---|---|---|---|
Zeile 1: | Zeile 1: | ||
+ | ====== Leerzeichen am Anfang / Ende einer Zeichenkette entfernen ====== | ||
+ | > Just as my fingers' | ||
+ | >> --- Herb Sutter | ||
+ | Am Anfang und/oder am Ende einer Zeichenkette stehende Leerzeichen (Tabulatoren, | ||
+ | Die Standardbibliothek bietet keine vorgefertigte Methode. | ||
+ | Die Suchmethoden der '' | ||
+ | <code cpp trim.cpp> | ||
+ | //: trim.cpp : Zeichen an Anfang/Ende eines string entfernen - R.Richter 2011-05-22 | ||
+ | /////////////////////////////////////////////////////////////////////////////////// | ||
+ | |||
+ | #include < | ||
+ | |||
+ | std::string rtrim(std:: | ||
+ | { | ||
+ | std:: | ||
+ | return last == std:: | ||
+ | } | ||
+ | |||
+ | std::string ltrim(std:: | ||
+ | { | ||
+ | return s.erase(0, s.find_first_not_of(delim.c_str())); | ||
+ | } | ||
+ | |||
+ | std::string trim(std:: | ||
+ | { | ||
+ | return ltrim(rtrim(s, | ||
+ | } | ||
+ | </ | ||
+ | Die Lösung ist allgemeiner anwendbar: | ||
+ | <code cpp> | ||
+ | std::string s = " Text "; | ||
+ | s = trim(s); | ||
+ | s = trim(" | ||
+ | </ | ||
+ | Sollen lediglich " | ||
+ | <code cpp> | ||
+ | std::string s = " Das ist ein Text "; | ||
+ | std:: | ||
+ | std::string wort; | ||
+ | |||
+ | while (in >> wort) | ||
+ | { | ||
+ | // ... wort verarbeiten | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ===== C++17 update ===== | ||
+ | C++17 erlaubt mit [[..: | ||
+ | |||
+ | <code cpp trim_sv.cpp> | ||
+ | #include < | ||
+ | |||
+ | auto trim(std:: | ||
+ | { | ||
+ | sv.remove_prefix(std:: | ||
+ | auto pos = sv.find_last_not_of(delimiters); | ||
+ | if (pos != sv.npos) sv.remove_suffix(sv.size() - (pos + 1)); | ||
+ | return sv; | ||
+ | } | ||
+ | </ | ||
+ | Der daraus entstandene Zeichenbereich lässt sich wie oben gezeigt auch wieder einem String zuweisen. |