From b578738870e83db4e61d6f6591bc73884108b7d4 Mon Sep 17 00:00:00 2001 From: David Kalnischkies Date: Sun, 7 Sep 2014 21:27:57 +0200 Subject: strip everything spacey in APT::String::Strip Git-Dch: Ignore --- apt-pkg/contrib/strutl.cc | 24 ++++++++++++++++++------ test/libapt/strutil_test.cc | 15 +++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/apt-pkg/contrib/strutl.cc b/apt-pkg/contrib/strutl.cc index 922229e90..87f57a30e 100644 --- a/apt-pkg/contrib/strutl.cc +++ b/apt-pkg/contrib/strutl.cc @@ -45,14 +45,26 @@ using namespace std; // --------------------------------------------------------------------- namespace APT { namespace String { -std::string Strip(const std::string &s) +std::string Strip(const std::string &str) { - size_t start = s.find_first_not_of(" \t\n"); - // only whitespace - if (start == string::npos) + // ensure we have at least one character + if (str.empty() == true) + return str; + + char const * const s = str.c_str(); + size_t start = 0; + for (; isspace(s[start]) != 0; ++start) + ; // find the first not-space + + // string contains only whitespaces + if (s[start] == '\0') return ""; - size_t end = s.find_last_not_of(" \t\n"); - return s.substr(start, end-start+1); + + size_t end = str.length() - 1; + for (; isspace(s[end]) != 0; --end) + ; // find the last not-space + + return str.substr(start, end - start + 1); } bool Endswith(const std::string &s, const std::string &end) diff --git a/test/libapt/strutil_test.cc b/test/libapt/strutil_test.cc index e9b778c6b..194c9c074 100644 --- a/test/libapt/strutil_test.cc +++ b/test/libapt/strutil_test.cc @@ -19,6 +19,21 @@ TEST(StrUtilTest,DeEscapeString) EXPECT_EQ("foo\\ x", DeEscapeString("foo\\\\ x")); EXPECT_EQ("\\foo\\", DeEscapeString("\\\\foo\\\\")); } +TEST(StrUtilTest,StringStrip) +{ + EXPECT_EQ("", APT::String::Strip("")); + EXPECT_EQ("foobar", APT::String::Strip("foobar")); + EXPECT_EQ("foo bar", APT::String::Strip("foo bar")); + + EXPECT_EQ("", APT::String::Strip(" ")); + EXPECT_EQ("", APT::String::Strip(" \r\n \t ")); + + EXPECT_EQ("foo bar", APT::String::Strip("foo bar ")); + EXPECT_EQ("foo bar", APT::String::Strip("foo bar \r\n \t ")); + EXPECT_EQ("foo bar", APT::String::Strip("\r\n \t foo bar")); + EXPECT_EQ("bar foo", APT::String::Strip("\r\n \t bar foo \r\n \t ")); + EXPECT_EQ("bar \t\r\n foo", APT::String::Strip("\r\n \t bar \t\r\n foo \r\n \t ")); +} TEST(StrUtilTest,StringSplitBasic) { std::vector result = StringSplit("", ""); -- cgit v1.2.3-70-g09d2