diff --git a/inc/util.h b/inc/util.h index 9cb0f1b..7a32667 100644 --- a/inc/util.h +++ b/inc/util.h @@ -32,6 +32,7 @@ bool trimOnce(std::string& str, char c = ' '); std::string bytesToBase16(char* buffer, unsigned int len); std::string bytesToBase64(char* buffer, unsigned int len); +bool replace(std::string& modify, const std::string& search, char replace); class StringSpliterator : public std::iterator { public: diff --git a/src/util.cpp b/src/util.cpp index a0a1393..5e4445b 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -183,6 +183,19 @@ std::string mrbesen::util::bytesToBase64(char* buffer, unsigned int len) { return ret; } +bool mrbesen::util::replace(std::string& modify, const std::string& search, char replace) { + bool changed = false; + for(size_t pos = modify.find_first_of(search); pos < std::string::npos; ) { + modify[pos] = replace; + changed = true; + + //search next + pos = modify.find_first_of(search, pos+1); + } + + return changed; +} + mrbesen::util::StringSpliterator::StringSpliterator(const std::string& d, const std::string& token) : data(d), token(token) { //trim diff --git a/tests/main.cpp b/tests/main.cpp index 86de8e9..7a80cec 100644 --- a/tests/main.cpp +++ b/tests/main.cpp @@ -17,6 +17,7 @@ int testUtil_insertStart_End(); int testUtil_trim(); int testUtil_trimOnce(); int testUtil_base(); +int testUtil_replace(); int testStringSpliterator(); int testUtilSplit(); @@ -24,7 +25,7 @@ int testUtilSplit(); int testGetDoy(); test_t tests[] = {testFiles_parent, testFiles_file, testFiles_extention, testFiles_scan, testFiles_readFile, - testUtil_Count, testUtil_equalsIgnoreCase, testUtil_toLower, testUtil_start_endWith, testUtil_removeStart_End, testUtil_insertStart_End, testUtil_trim, testUtil_trimOnce, testUtil_base, + testUtil_Count, testUtil_equalsIgnoreCase, testUtil_toLower, testUtil_start_endWith, testUtil_removeStart_End, testUtil_insertStart_End, testUtil_trim, testUtil_trimOnce, testUtil_base, testUtil_replace, testStringSpliterator, testUtilSplit, testGetDoy, NULL}; diff --git a/tests/utilstest.cpp b/tests/utilstest.cpp index 6d475ab..7914398 100644 --- a/tests/utilstest.cpp +++ b/tests/utilstest.cpp @@ -222,5 +222,20 @@ int testUtil_base() { ret = bytesToBase64(buf, 6); ASSERT(ret == "AKsSzTT_", ret); + return TESTGOOD; +} + +int testUtil_replace() { + std::string test = "#abc#def#"; + + ASSERT(!replace(test, "", ' '), ""); + ASSERT(test == "#abc#def#", test); + ASSERT(!replace(test, "xyz", ' '), ""); + ASSERT(test == "#abc#def#", test); + ASSERT(replace(test, "af", ' '), ""); + ASSERT(test == "# bc#de #", test); + ASSERT(replace(test, "#q ", ' '), ""); + ASSERT(test == " bc de ", test); + return TESTGOOD; } \ No newline at end of file