I want to make sure find_value_from_key()
is safe and efficient. My constraints are language C++, use of standard library ok, but cannot use Boost or any new C++11 features.
Can anyone offer any comments/criticisms/feedback on my implementation of the function here? Any flaws in my test cases would also be interesting to hear.
#include <string>
#include <iostream>
using std::cout;
using std::endl;
using std::string;
bool find_value_from_key(const string& source, const string& key, string& value, const string& EndOfValueMarker) {
bool ret = false;
size_t pos_start = source.find(key);
if(pos_start != string::npos) {
size_t pos_end = source.find_first_of(EndOfValueMarker, pos_start+key.length());
if(pos_end == string::npos && source.length() > pos_start+key.length())
pos_end = source.length();
if(pos_end != string::npos) {
value = source.substr(pos_start+key.length(), pos_end-pos_start-key.length());
ret = true;
}
}
return ret;
}
int main(int argc, char* argv[])
{
//test strings to exercise find_value_from_key function
const char* test_strings[] = {
"key1 = value1",
" key1 = value1 ",
"key1 = value1,key2 = value2 ,key3 = value3",
"_key1 = value1 ,key2 = value2 ,Gkey3 = value3,",
"key1 = value1,key2 = value2 ,key3 = value3 x",
"key1 = value1,key2 = value2key3 = value3\n",
"key1 = value1_,key2 = value2 ,key3 = value3 ",
"key1 = value1$,key2 = value2 ,key3 = value3",
"key1 = value1\t,key2 = value2 ,key3 = value3\t" };
const char* keys[] = {"key1 = ", "key2 = ", "key3 = "};
int elements = sizeof(test_strings) / sizeof(test_strings[0]);
for(int i = 0; i < elements; ++i) {
cout << "processing: " << test_strings[i] << endl;
string value;
if(find_value_from_key(test_strings[0], keys[0], value, ", \t\n"))
cout << value << endl;
}
return 0;
}