From b81d6d6744aad07049cb4f12d14d71fc89a787e5 Mon Sep 17 00:00:00 2001 From: mizipzor Date: Thu, 18 Feb 2010 18:53:48 +0100 Subject: [PATCH] added string splitter to digger, to handle comma delimited arguments --- tools/digger.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) diff --git a/tools/digger.cpp b/tools/digger.cpp index a667bcb8b..f0584bfc5 100644 --- a/tools/digger.cpp +++ b/tools/digger.cpp @@ -23,6 +23,7 @@ using namespace std; #include #include +// counts the occurances of a certain element in a vector int vec_count(vector& vec, uint16_t t) { int count = 0; @@ -33,7 +34,27 @@ int vec_count(vector& vec, uint16_t t) } return count; } + +// splits a string on a certain char +// +// src is the string to split +// delim is the delimiter to split the string around +// tokens is filled with every occurance between delims +void string_split(vector& tokens, const std::string& src, const std::string& delim) +{ + std::string::size_type start = 0; + std::string::size_type end; + while (true) + { + end = src.find(delim, start); + tokens.push_back(src.substr(start, end - start)); + if (end == std::string::npos) // last token handled + break; + start = end + delim.size(); // skip next delim + } +} +// calculates the manhattan distance between two coords int manhattan_distance(int x, int y, int z, int xx, int yy, int zz) { return abs(x-xx)+abs(y-yy)+abs(z-zz); @@ -179,6 +200,8 @@ int dig(DFHack::API& DF, void test() { + ////////////////////////// + // DigTarget { DigTarget dt( 20, 35, 16, @@ -196,7 +219,6 @@ void test() assert(dt.z == 16); assert(dt.source_distance == 35); } - { DigTarget dt( 2, 4, 16, @@ -215,6 +237,29 @@ void test() assert(dt.z == 16); assert(dt.source_distance == 91); } + + ////////////////////////// + // string splitter + { + vector tokens; + string src = "10,9,11"; + string delim = ","; + string_split(tokens, src, delim); + + assert(tokens.size() == 3); + assert(tokens[0] == "10"); + assert(tokens[1] == "9"); + assert(tokens[2] == "11"); + } + { + vector tokens; + string src = "10"; + string delim = ","; + string_split(tokens, src, delim); + + assert(tokens.size() == 1); + assert(tokens[0] == "10"); + } } int main (int argc, const char* argv[])