SplitString.h 1.7 KB

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