Add removeStringEnd()
authorPerttu Ahola <celeron55@gmail.com>
Sun, 25 Mar 2012 09:48:14 +0000 (12:48 +0300)
committerPerttu Ahola <celeron55@gmail.com>
Sun, 25 Mar 2012 11:48:14 +0000 (14:48 +0300)
src/test.cpp
src/utility_string.h

index 6588f113c4d622975685cf7d29f43f48c85948cd..1b9dfcb5dcf0c4c9b6546d090b351a2d8a3fa309 100644 (file)
@@ -35,6 +35,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
 #include "mapsector.h"
 #include "settings.h"
 #include "log.h"
+#include "utility_string.h"
 
 /*
        Asserts that the exception occurs
@@ -120,6 +121,11 @@ struct TestUtilities
                assert(is_yes("YeS") == true);
                assert(is_yes("") == false);
                assert(is_yes("FAlse") == false);
+               const char *ends[] = {"abc", "c", "bc", NULL};
+               assert(removeStringEnd("abc", ends) == "");
+               assert(removeStringEnd("bc", ends) == "b");
+               assert(removeStringEnd("12c", ends) == "12");
+               assert(removeStringEnd("foo", ends) == "");
        }
 };
 
index f29057ad7cd977944f75a4cf8ea5a48dbc8dd10b..df283ba69949cb7f0f095970a59a92b67b93bb1e 100644 (file)
@@ -31,5 +31,20 @@ static inline std::string padStringRight(std::string s, size_t len)
        return s;
 }
 
+// ends: NULL- or ""-terminated array of strings
+// Returns "" if no end could be removed.
+static inline std::string removeStringEnd(const std::string &s, const char *ends[])
+{
+       const char **p = ends;
+       for(; (*p) && (*p)[0] != '\0'; p++){
+               std::string end = *p;
+               if(s.size() < end.size())
+                       continue;
+               if(s.substr(s.size()-end.size(), end.size()) == end)
+                       return s.substr(0, s.size() - end.size());
+       }
+       return "";
+}
+
 #endif