strip everything spacey in APT::String::Strip
authorDavid Kalnischkies <david@kalnischkies.de>
Sun, 7 Sep 2014 19:27:57 +0000 (21:27 +0200)
committerDavid Kalnischkies <david@kalnischkies.de>
Sun, 7 Sep 2014 19:27:57 +0000 (21:27 +0200)
Git-Dch: Ignore

apt-pkg/contrib/strutl.cc
test/libapt/strutil_test.cc

index 922229e..87f57a3 100644 (file)
@@ -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)
index e9b778c..194c9c0 100644 (file)
@@ -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<std::string> result = StringSplit("", "");