fork(1) download
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <vector>
  5. #include <utility>
  6.  
  7. using StrView = std::pair<const char*, size_t>;
  8.  
  9. StrView makeStrView(const char *str, size_t size) {
  10. return std::make_pair(str, size);
  11. }
  12.  
  13. struct compareStrView {
  14. bool operator()(const StrView &lhs, const StrView &rhs) const {
  15. if (lhs.second == rhs.second)
  16. return (std::char_traits<char>::compare(lhs.first, rhs.first, lhs.second) < 0);
  17. return (lhs.second < rhs.second);
  18. }
  19. };
  20.  
  21. std::ostream& operator<<(std::ostream &os, const StrView &rhs) {
  22. return os.write(rhs.first, rhs.second);
  23. }
  24.  
  25. int main() {
  26. std::string str("0=My,1=comma,2=separated,3=string,0=with,3=repeated,7=IDs");
  27. std::vector<StrView> out0;
  28. std::map<StrView, StrView, compareStrView> out;
  29.  
  30. size_t startPos = 0, delimPos, nameStart, nameEnd, valueStart, valueEnd;
  31.  
  32. // loop over the string, collecting "key=value" pairs
  33. while (startPos < str.size()){
  34. nameStart = startPos;
  35. delimPos = str.find_first_of("=,", startPos, 2);
  36. if (delimPos == std::string::npos) {
  37. nameEnd = valueStart = valueEnd = str.size();
  38. }
  39. else {
  40. nameEnd = delimPos;
  41. if (str[delimPos] == '=') {
  42. valueStart = nameEnd + 1;
  43. valueEnd = str.find(',', valueStart);
  44. if (valueEnd == std::string::npos) {
  45. valueEnd = str.size();
  46. }
  47. }
  48. else {
  49. valueStart = valueEnd = nameEnd;
  50. }
  51. }
  52.  
  53. // TODO: if needed, adjust nameStart/End and valueStartEnd to
  54. // ignore leading/trailing whitespace around the name and value
  55. // substrings...
  56.  
  57. if (str.compare(nameStart, nameEnd - nameStart, "0", 1) == 0) {
  58. out0.push_back(makeStrView(&str[valueStart], valueEnd - valueStart));
  59. } else {
  60. out[makeStrView(&str[nameStart], nameEnd - nameStart)] = makeStrView(&str[valueStart], valueEnd - valueStart);
  61. }
  62.  
  63. startPos = valueEnd + 1;
  64. }
  65.  
  66. // print out the data structures
  67. std::cout << "out0:";
  68. for (auto& entry : out0) {
  69. std::cout << ' ' << entry;
  70. }
  71. std::cout << std::endl;
  72.  
  73. std::cout << "out:";
  74. for (auto &it : out) {
  75. std::cout << ' ' << it.first << '=' << it.second;
  76. }
  77. }
Success #stdin #stdout 0s 4576KB
stdin
Standard input is empty
stdout
out0: My with
out: 1=comma 2=separated 3=repeated 7=IDs