SplitString.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #ifndef SPLITSTRING_H
  2. #define SPLITSTRING_H
  3. #include "utils/List.h"
  4. #include "utils/StringBuffer.h"
  5. template<int N>
  6. class SplitString final {
  7. List<int, N> entries;
  8. List<char, N> data;
  9. bool fill(const StringBuffer<N>& s) {
  10. for(int i = 0; i < s.getLength(); i++) {
  11. switch(s[i]) {
  12. case ' ':
  13. handleSpace(s, i);
  14. break;
  15. case '"':
  16. if(handleQuotation(s, i)) {
  17. return true;
  18. }
  19. break;
  20. default:
  21. data.add(s[i]);
  22. }
  23. }
  24. data.add('\0');
  25. return false;
  26. }
  27. void handleSpace(const StringBuffer<N>& s, int& i) {
  28. while(i + 1 < s.getLength() && s[i + 1] == ' ') {
  29. i++;
  30. }
  31. if(i + 1 < s.getLength()) {
  32. data.add('\0');
  33. }
  34. }
  35. bool handleQuotation(const StringBuffer<N>& s, int& i) {
  36. if(i != 0 && s[i - 1] != ' ') {
  37. return true;
  38. }
  39. i++;
  40. while(i < s.getLength() && s[i] != '"') {
  41. data.add(s[i++]);
  42. }
  43. if(i >= s.getLength() || (i != s.getLength() - 1 && s[i + 1] != ' ')) {
  44. return true;
  45. }
  46. return false;
  47. }
  48. void addEntries() {
  49. int lastIndex = 0;
  50. for(int i = 0; i < data.getLength(); i++) {
  51. if(data[i] == '\0') {
  52. entries.add(lastIndex);
  53. lastIndex = i + 1;
  54. }
  55. }
  56. }
  57. public:
  58. SplitString(const StringBuffer<N>& s) {
  59. if(fill(s)) {
  60. return;
  61. }
  62. addEntries();
  63. }
  64. int getLength() const {
  65. return entries.getLength();
  66. }
  67. const char* operator[](int index) const {
  68. return &(data[entries[index]]);
  69. }
  70. };
  71. #endif