Skip to content

Commit

Permalink
Add Core::StringUtil::trim() to remove whitespace from strings
Browse files Browse the repository at this point in the history
I thought I needed this, but it turns out I didn't. It's just dead code
now; I'm leaving it in as it may be useful later.
  • Loading branch information
ongardie authored and Nate Hardt committed Aug 20, 2015
1 parent 5c0069d commit 5db9c58
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
24 changes: 24 additions & 0 deletions Core/StringUtil.cc
Expand Up @@ -20,8 +20,11 @@

#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdarg>
#include <cstring>
#include <functional>
#include <locale>
#include <sstream>

#include "Core/StringUtil.h"
Expand Down Expand Up @@ -160,6 +163,27 @@ endsWith(const std::string& haystack, const std::string& needle)
needle.length(), needle) == 0);
}

std::string
trim(const std::string& original)
{
// The black magic is from https://stackoverflow.com/a/217605
std::string s = original;

// trim whitespace at end of string
s.erase(std::find_if(s.rbegin(), s.rend(),
std::not1(std::ptr_fun<int, int>(std::isspace)))
.base(),
s.end());

// trim whitespace at beginning of string
s.erase(s.begin(),
std::find_if(s.begin(), s.end(),
std::not1(std::ptr_fun<int, int>(std::isspace))));

return s;
}


} // namespace LogCabin::Core::StringUtil
} // namespace LogCabin::Core
} // namespace LogCabin
6 changes: 6 additions & 0 deletions Core/StringUtil.h
Expand Up @@ -121,6 +121,12 @@ toString(const T& t)
return ss.str();
}

/**
* Return a copy of the given string except with no leading or trailing
* whitespace.
*/
std::string trim(const std::string& s);

} // namespace LogCabin::Core::StringUtil
} // namespace LogCabin::Core
} // namespace LogCabin
Expand Down
7 changes: 7 additions & 0 deletions Core/StringUtilTest.cc
Expand Up @@ -113,6 +113,13 @@ TEST(CoreStringUtilTest, toString) {
EXPECT_EQ("3", toString(3));
}

TEST(CoreStringUtilTest, trim) {
EXPECT_EQ("abc", trim("abc"));
EXPECT_EQ("abc", trim(" abc "));
EXPECT_EQ("abc", trim("\tabc\n"));
EXPECT_EQ("", trim(" "));
}

} // namespace LogCabin::Core::StringUtil::<anonymous>
} // namespace LogCabin::Core::StringUtil
} // namespace LogCabin::Core
Expand Down

0 comments on commit 5db9c58

Please sign in to comment.