diff options
author | Eliot Horowitz <eliot@10gen.com> | 2010-05-26 15:04:56 -0400 |
---|---|---|
committer | Eliot Horowitz <eliot@10gen.com> | 2010-05-26 15:04:56 -0400 |
commit | 3ffcb16346d34b614c8ffccf869efb2ce37f2a4b (patch) | |
tree | 3435777509ee6833252486d2b982e7c74f12812e | |
parent | 2418b8cd35127f0ce522fb830379820ebb3404e7 (diff) | |
download | mongo-3ffcb16346d34b614c8ffccf869efb2ce37f2a4b.tar.gz |
some text utilities
-rw-r--r-- | dbtests/basictests.cpp | 19 | ||||
-rw-r--r-- | util/text.h | 63 |
2 files changed, 82 insertions, 0 deletions
diff --git a/dbtests/basictests.cpp b/dbtests/basictests.cpp index 666d9aae536..1bb071dad9f 100644 --- a/dbtests/basictests.cpp +++ b/dbtests/basictests.cpp @@ -22,6 +22,7 @@ #include "dbtests.h" #include "../util/base64.h" #include "../util/array.h" +#include "../util/text.h" namespace BasicTests { @@ -408,6 +409,22 @@ namespace BasicTests { } }; + struct StringSplitterTest { + + void test( string s ){ + vector<string> v = StringSplitter::split( s , "," ); + ASSERT_EQUALS( s , StringSplitter::join( v , "," ) ); + } + + void run(){ + test( "a" ); + test( "a,b" ); + test( "a,b,c" ); + } + }; + + + class All : public Suite { public: All() : Suite( "basic" ){ @@ -431,6 +448,8 @@ namespace BasicTests { add< DatabaseValidNames >(); add< PtrTests >(); + + add< StringSplitterTest >(); } } myall; diff --git a/util/text.h b/util/text.h new file mode 100644 index 00000000000..ba7977dfee5 --- /dev/null +++ b/util/text.h @@ -0,0 +1,63 @@ +// text.h + +#pragma once + +namespace mongo { + + class StringSplitter { + public: + StringSplitter( const char * big , const char * splitter ) + : _big( big ) , _splitter( splitter ){ + } + + bool more(){ + return _big[0]; + } + + string next(){ + const char * foo = strstr( _big , _splitter ); + if ( foo ){ + string s( _big , foo - _big ); + _big = foo + 1; + return s; + } + + string s = _big; + _big += strlen( _big ); + return s; + } + + void split( vector<string>& l ){ + while ( more() ){ + l.push_back( next() ); + } + } + + vector<string> split(){ + vector<string> l; + split( l ); + return l; + } + + static vector<string> split( const string& big , const string& splitter ){ + StringSplitter ss( big.c_str() , splitter.c_str() ); + return ss.split(); + } + + static string join( vector<string>& l , const string& split ){ + stringstream ss; + for ( unsigned i=0; i<l.size(); i++ ){ + if ( i > 0 ) + ss << split; + ss << l[i]; + } + return ss.str(); + } + + private: + const char * _big; + const char * _splitter; + }; + + +} |