Skip to content

Commit

Permalink
add strip_whitespace
Browse files Browse the repository at this point in the history
  • Loading branch information
fuzziqersoftware committed Apr 13, 2024
1 parent 076b037 commit 7512997
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Strings.hh
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,23 @@ void strip_leading_whitespace(StrT& s) {
}
}

template <typename StrT>
void strip_whitespace(StrT& s) {
size_t start_index = s.find_first_not_of(" \t\r\n");
size_t end_index = s.find_last_not_of(" \t\r\n");
fprintf(stderr, "%zu %zu\n", start_index, end_index);
if (start_index != StrT::npos && end_index != StrT::npos) {
if (start_index) {
s = s.substr(start_index, end_index - start_index + 1);
} else {
s.resize(end_index + 1);
}
} else if (!s.empty() &&
((s[0] == ' ') || (s[0] == '\t') || (s[0] == '\r') || (s[0] == '\n'))) {
s.resize(0); // String is entirely whitespace
}
}

std::string escape_quotes(const std::string& s);
std::string escape_url(const std::string& s, bool escape_slash = false);

Expand Down
29 changes: 29 additions & 0 deletions src/StringsTest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,35 @@ int main(int, char**) {
expect_eq(s5, "");
}

{
fprintf(stderr, "-- strip_whitespace\n");

string s = "abcdef";
strip_whitespace(s);
fprintf(stderr, "%s\n", s.c_str());
expect_eq(s, "abcdef");

s = "abcdef\r\n";
strip_whitespace(s);
expect_eq(s, "abcdef");

s = " \nabc\tdef";
strip_whitespace(s);
expect_eq(s, "abc\tdef");

s = " \nabc\tdef \r\n";
strip_whitespace(s);
expect_eq(s, "abc\tdef");

s = "";
strip_whitespace(s);
expect_eq(s, "");

s = " \t\r\n ";
strip_whitespace(s);
expect_eq(s, "");
}

{
fprintf(stderr, "-- string_printf\n");
string result = string_printf("%s %" PRIu64 " 0x%04hX", "lolz",
Expand Down

0 comments on commit 7512997

Please sign in to comment.