Commit d0002eca authored by Alexander Zinoviev's avatar Alexander Zinoviev Committed by Facebook Github Bot

trim, ltrim, rtrim functions with custom predicate

Summary: trim, ltrim and rtrim are similar to ltrimWhitespace, rtrimWhitespace and trimWhitespace but you can specify what you want to remove

Reviewed By: yfeldblum

Differential Revision: D17946658

fbshipit-source-id: 9bdc5e6eb810e628a8c16b5142c17a3313f884f2
parent 8c7a26ad
...@@ -580,6 +580,41 @@ inline StringPiece skipWhitespace(StringPiece sp) { ...@@ -580,6 +580,41 @@ inline StringPiece skipWhitespace(StringPiece sp) {
return ltrimWhitespace(sp); return ltrimWhitespace(sp);
} }
/**
* Returns a subpiece with all characters the provided @toTrim returns true
* for removed from the front of @sp.
*/
template <typename ToTrim>
StringPiece ltrim(StringPiece sp, ToTrim toTrim) {
while (!sp.empty() && toTrim(sp.front())) {
sp.pop_front();
}
return sp;
}
/**
* Returns a subpiece with all characters the provided @toTrim returns true
* for removed from the back of @sp.
*/
template <typename ToTrim>
StringPiece rtrim(StringPiece sp, ToTrim toTrim) {
while (!sp.empty() && toTrim(sp.back())) {
sp.pop_back();
}
return sp;
}
/**
* Returns a subpiece with all characters the provided @toTrim returns true
* for removed from the back and front of @sp.
*/
template <typename ToTrim>
StringPiece trim(StringPiece sp, ToTrim toTrim) {
return ltrim(rtrim(sp, std::ref(toTrim)), std::ref(toTrim));
}
/** /**
* Strips the leading and the trailing whitespace-only lines. Then looks for * Strips the leading and the trailing whitespace-only lines. Then looks for
* the least indented non-whitespace-only line and removes its amount of * the least indented non-whitespace-only line and removes its amount of
......
...@@ -1258,6 +1258,26 @@ TEST(String, whitespace) { ...@@ -1258,6 +1258,26 @@ TEST(String, whitespace) {
EXPECT_EQ("", rtrimWhitespace("\r ")); EXPECT_EQ("", rtrimWhitespace("\r "));
} }
TEST(String, trim) {
auto removeA = [](const char c) { return 'a' == c; };
auto removeB = [](const char c) { return 'b' == c; };
// trim:
EXPECT_EQ("akavabanga", trim("akavabanga", removeB));
EXPECT_EQ("kavabang", trim("akavabanga", removeA));
EXPECT_EQ("kavabang", trim("aakavabangaa", removeA));
// ltrim:
EXPECT_EQ("akavabanga", ltrim("akavabanga", removeB));
EXPECT_EQ("kavabanga", ltrim("akavabanga", removeA));
EXPECT_EQ("kavabangaa", ltrim("aakavabangaa", removeA));
// rtrim:
EXPECT_EQ("akavabanga", rtrim("akavabanga", removeB));
EXPECT_EQ("akavabang", rtrim("akavabanga", removeA));
EXPECT_EQ("aakavabang", rtrim("aakavabangaa", removeA));
}
TEST(String, stripLeftMargin_really_empty) { TEST(String, stripLeftMargin_really_empty) {
auto input = ""; auto input = "";
auto expected = ""; auto expected = "";
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment