add maxsplit parameter to StringSplit
authorMichael Vogt <mvo@debian.org>
Sat, 7 Sep 2013 11:12:50 +0000 (13:12 +0200)
committerMichael Vogt <mvo@debian.org>
Sat, 7 Sep 2013 11:12:50 +0000 (13:12 +0200)
apt-pkg/contrib/strutl.cc
apt-pkg/contrib/strutl.h
test/libapt/strutil_test.cc

index 819d50d..508af89 100644 (file)
@@ -1123,19 +1123,27 @@ vector<string> VectorizeString(string const &haystack, char const &split)
 /* This can be used to split a given string up into a vector of strings
  * The seperator is a string
  */
-vector<string> StringSplit(string const &s, std::string const &sep)
+vector<string> StringSplit(string const &s, std::string const &sep,
+                           unsigned int maxsplit)
 {
    vector<string> split;
    size_t start, pos;
-   start = pos = 0;
+
    if(sep.size() == 0)
       return split;
-   
+
+   start = pos = 0;
    do {
       pos = s.find(sep, start);
       split.push_back(s.substr(start, pos-start));
-      if(pos != string::npos)
-         start = pos+sep.size();
+      
+      // deal with the max-split
+      if(maxsplit > 0 && split.size() >= maxsplit)
+      {
+         split[split.size()-1] = s.substr(start);
+         break;
+      }
+      start = pos+sep.size();
    } while (pos != string::npos);
    return split;
 }
index c97246c..944f914 100644 (file)
@@ -66,7 +66,7 @@ bool TokSplitString(char Tok,char *Input,char **List,
                    unsigned long ListMax);
 std::vector<std::string> VectorizeString(std::string const &haystack, char const &split) __attrib_const;
 // like python string.split
-std::vector<std::string> StringSplit(std::string const &haystack, std::string const &sep) __attrib_const;
+std::vector<std::string> StringSplit(std::string const &haystack, std::string const &sep, unsigned int maxsplit=0) __attrib_const;
 void ioprintf(std::ostream &out,const char *format,...) __like_printf(2);
 void strprintf(std::string &out,const char *format,...) __like_printf(2);
 char *safe_snprintf(char *Buffer,char *End,const char *Format,...) __like_printf(3);
index bac9dd2..b044b7f 100644 (file)
@@ -59,5 +59,11 @@ int main(int argc,char *argv[])
    result = StringSplit(input, "");
    equals(result.size(), 0);
 
+   input = "x:y:z";
+   result = StringSplit(input, ":", 2);
+   equals(result.size(), 2);
+   equals(result[0], "x");
+   equals(result[1], "y:z");
+
    return 0;
 }