fork download
  1. #include <stdio.h>
  2. #include <string>
  3. #include <iostream>
  4.  
  5. using std::cout;
  6. using std::endl;
  7. using std::string;
  8.  
  9.  
  10. bool find_value_from_key(const string& source, const string& key, string& value, const string& endmarkers) {
  11. bool ret = false;
  12. size_t key_start = source.find(key);
  13. size_t val_start = key_start + key.length();
  14. if(key_start != string::npos) {
  15. size_t val_end = source.find_first_of(endmarkers, val_start);
  16. if(val_end == string::npos && source.length() > val_start)
  17. val_end = source.length();
  18.  
  19. if(val_end != string::npos) {
  20. value = source.substr(val_start, val_end - val_start);
  21. ret = true;
  22. }
  23. }
  24. return ret;
  25. }
  26.  
  27. int main(int argc, char* argv[])
  28. {
  29. //test strings to exercise find_value_from_key function
  30. const char* test_strings[] = {
  31. "key1 = value1",
  32. " key1 = value1 ",
  33. "key1 = value1,key2 = value2 ,key3 = value3",
  34. "_key1 = value1 ,key2 = value2 ,Gkey3 = value3,",
  35. "key1 = value1,key2 = value2 ,key3 = value3 x",
  36. "key1 = value1,key2 = value2key3 = value3\n",
  37. "key1 = value1_,key2 = value2 ,key3 = value3 ",
  38. "key1 = value1$,key2 = value2 ,key3 = value3",
  39. "key1 = value1\t,key2 = value2 ,key3 = value3\t" };
  40.  
  41. const char* keys[] = {"key1 = ", "key2 = ", "key3 = "};
  42.  
  43. int elements = sizeof(test_strings) / sizeof(test_strings[0]);
  44.  
  45. for(int i = 0; i < elements; ++i) {
  46. cout << "processing: " << test_strings[i] << endl;
  47. string value;
  48. for (int k = 0; k < 3; k++) {
  49. if(find_value_from_key(test_strings[i], keys[k], value, ", \t\n"))
  50. cout << keys[k] << " -> " << value << endl;
  51. }
  52. }
  53.  
  54. return 0;
  55. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
processing: key1 = value1
key1 =  -> value1
processing:    key1 = value1   
key1 =  -> value1
processing: key1 = value1,key2 = value2 ,key3 = value3
key1 =  -> value1
key2 =  -> value2
key3 =  -> value3
processing: _key1 = value1 ,key2 = value2 ,Gkey3 = value3,
key1 =  -> value1
key2 =  -> value2
key3 =  -> value3
processing: key1 = value1,key2 =  value2 ,key3 = value3 x
key1 =  -> value1
key2 =  -> 
key3 =  -> value3
processing: key1 = value1,key2 = value2key3 = value3

key1 =  -> value1
key2 =  -> value2key3
key3 =  -> value3
processing: key1 = value1_,key2 = value2 ,key3 = value3                    
key1 =  -> value1_
key2 =  -> value2
key3 =  -> value3
processing: key1 = value1$,key2 = value2 ,key3 =   value3
key1 =  -> value1$
key2 =  -> value2
key3 =  -> 
processing: key1 = value1	,key2 = value2  ,key3 = value3	
key1 =  -> value1
key2 =  -> value2
key3 =  -> value3