CommandUtils.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "CommandUtils.h"
  2. #include <iostream>
  3. bool CommandUtils::splitString(const string& rawCommand, string& command, vector<string>& args)
  4. {
  5. bool b = splitStringIntern(rawCommand, command, args);
  6. if(b)
  7. {
  8. args.clear();
  9. command = "";
  10. }
  11. return b;
  12. }
  13. bool CommandUtils::splitStringIntern(const string& rawCommand, string& command, vector<string>& args)
  14. {
  15. int old = 0;
  16. int index = 0;
  17. // parse first argument
  18. while(index < rawCommand.size())
  19. {
  20. if(rawCommand[index] == ' ')
  21. {
  22. command = rawCommand.substr(old, index - old);
  23. old = index + 1;
  24. index++;
  25. break;
  26. }
  27. index++;
  28. }
  29. // if the command name is the whole raw command
  30. if(index == rawCommand.size())
  31. {
  32. command = rawCommand.substr(old, index - old);
  33. return false;
  34. }
  35. // parse remainding arguments
  36. while(index < rawCommand.size())
  37. {
  38. if(rawCommand[index] == '"')
  39. {
  40. // no space before the quotation mark
  41. if(index != old)
  42. {
  43. return true;
  44. }
  45. old = index + 1;
  46. while(true)
  47. {
  48. index++;
  49. // quotation mark not closed
  50. if(index >= rawCommand.size())
  51. {
  52. return true;
  53. }
  54. else if(rawCommand[index] == '"')
  55. {
  56. break;
  57. }
  58. }
  59. // no space after quotation mark
  60. if(index + 1 < rawCommand.size() && rawCommand[index + 1] != ' ')
  61. {
  62. return true;
  63. }
  64. args.push_back(rawCommand.substr(old, index - old));
  65. old = index + 2;
  66. }
  67. else if(rawCommand[index] == ' ')
  68. {
  69. if(index - old > 0)
  70. {
  71. args.push_back(rawCommand.substr(old, index - old));
  72. }
  73. old = index + 1;
  74. }
  75. index++;
  76. }
  77. if(index > old && index - old > 0)
  78. {
  79. args.push_back(rawCommand.substr(old, index - old));
  80. }
  81. return false;
  82. }