summaryrefslogtreecommitdiff
path: root/src/core/common
diff options
context:
space:
mode:
authorAndreas Stöckel <astoecke@techfak.uni-bielefeld.de>2015-01-24 03:06:19 +0100
committerAndreas Stöckel <astoecke@techfak.uni-bielefeld.de>2015-01-24 03:06:19 +0100
commitfcdc9e28805138383c6ef662ea5e3822720b772c (patch)
tree50e27515357e3924e74de8b92850f9cbce1c373c /src/core/common
parent18d3637ca02ab69f1ee744fa94c43c243de0f571 (diff)
Added generic trim function
Diffstat (limited to 'src/core/common')
-rw-r--r--src/core/common/Utils.cpp16
-rw-r--r--src/core/common/Utils.hpp47
2 files changed, 49 insertions, 14 deletions
diff --git a/src/core/common/Utils.cpp b/src/core/common/Utils.cpp
index c8fcdc6..f59061a 100644
--- a/src/core/common/Utils.cpp
+++ b/src/core/common/Utils.cpp
@@ -27,20 +27,8 @@ namespace ousia {
std::string Utils::trim(const std::string &s)
{
- size_t firstNonWhitespace = std::numeric_limits<size_t>::max();
- size_t lastNonWhitespace = 0;
- for (size_t i = 0; i < s.size(); i++) {
- if (!isWhitespace(s[i])) {
- firstNonWhitespace = std::min(i, firstNonWhitespace);
- lastNonWhitespace = std::max(i, lastNonWhitespace);
- }
- }
-
- if (firstNonWhitespace < lastNonWhitespace) {
- return s.substr(firstNonWhitespace,
- lastNonWhitespace - firstNonWhitespace + 1);
- }
- return std::string{};
+ std::pair<size_t, size_t> bounds = trim(s, Utils::isWhitespace);
+ return s.substr(bounds.first, bounds.second - bounds.first);
}
bool Utils::isIdentifier(const std::string &name)
diff --git a/src/core/common/Utils.hpp b/src/core/common/Utils.hpp
index 22e0fd3..f6f5225 100644
--- a/src/core/common/Utils.hpp
+++ b/src/core/common/Utils.hpp
@@ -71,11 +71,58 @@ public:
}
/**
+ * Returns true if the given character is a whitespace character.
+ */
+ static bool isLinebreak(const char c)
+ {
+ return (c == '\n') || (c == '\r');
+ }
+
+ /**
* Removes whitespace at the beginning and the end of the given string.
+ *
+ * @param s is the string that should be trimmed.
+ * @return a trimmed copy of s.
*/
static std::string trim(const std::string &s);
/**
+ * Trims the given string or vector of chars by returning the start and end
+ * index.
+ *
+ * @param s is the container that should be trimmed.
+ * @param f is a function that returns true for values that should be
+ * removed.
+ * @return start and end index. Note that "end" points at the character beyond
+ * the end, thus "end" minus "start"
+ */
+ template <class T, class Filter>
+ static std::pair<size_t, size_t> trim(const T &s, Filter f) {
+ size_t start = 0;
+ for (size_t i = 0; i < s.size(); i++) {
+ if (!f(s[i])) {
+ start = i;
+ break;
+ }
+ }
+
+ size_t end = 0;
+ for (ssize_t i = s.size() - 1; i >= static_cast<ssize_t>(start); i--) {
+ if (!f(s[i])) {
+ end = i + 1;
+ break;
+ }
+ }
+
+ if (end < start) {
+ start = 0;
+ end = 0;
+ }
+
+ return std::pair<size_t, size_t>{start, end};
+ }
+
+ /**
* Turns the elements of a collection into a string separated by the
* given delimiter.
*