From 445b57588da52b3e10a1b759e7723afe6687eb7a Mon Sep 17 00:00:00 2001 From: Manuel Reimer Date: Fri, 9 Nov 2018 22:04:33 +0100 Subject: Improved trim function --- strfct.c | 24 +++++++----------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/strfct.c b/strfct.c index adafae1..445353e 100644 --- a/strfct.c +++ b/strfct.c @@ -28,6 +28,7 @@ #include #include +#include #include "strfct.h" @@ -45,23 +46,12 @@ char * strncopy(char * dest , const char * src , size_t n) std::string trim(const std::string & s) { - std::string::size_type start, end; - - start = 0; - while (start < s.length()) - { - if (!isspace(s[start])) - break; - start++; - } - end = s.length() - 1; - while (end >= 0) - { - if (!isspace(s[end])) - break; - end--; - } - return s.substr(start, end - start + 1); + std::string::size_type left, right; + left = std::find_if_not(s.begin(), s.end(), isspace) - s.begin(); + if (left == s.length()) // String consists of space characters only + return ""; + right = std::find_if_not(s.rbegin(), s.rend(), isspace) - s.rbegin(); + return s.substr(left, s.length() - left - right); } std::string compactspace(const std::string & s) -- cgit v1.2.3