strparse.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include <string>
  2. #include <cstring>
  3. // #include <iostream> -- for debugging (cout)
  4. #include "ctype.h"
  5. using namespace std;
  6. #include "strparse.h"
  7. void String_parse::skip_space()
  8. {
  9. while ((*str)[pos] && isspace((*str)[pos])) {
  10. pos = pos + 1;
  11. }
  12. }
  13. char String_parse::peek()
  14. {
  15. return (*str)[pos];
  16. }
  17. void String_parse::get_nonspace_quoted(string &field)
  18. {
  19. field.clear();
  20. skip_space();
  21. bool quoted = false;
  22. if ((*str)[pos] == '"') {
  23. quoted = true;
  24. field.append(1, '"');
  25. pos = pos + 1;
  26. }
  27. while ((*str)[pos] && (quoted || !isspace((*str)[pos]))) {
  28. if ((*str)[pos] == '"') {
  29. if (quoted) {
  30. field.append(1, '"');
  31. pos = pos + 1;
  32. }
  33. return;
  34. }
  35. if ((*str)[pos] == '\\') {
  36. pos = pos + 1;
  37. }
  38. if ((*str)[pos]) {
  39. field.append(1, (*str)[pos]);
  40. pos = pos + 1;
  41. }
  42. }
  43. }
  44. static const char *const escape_chars[] = {"\\n", "\\t", "\\\\", "\\r", "\\\""};
  45. void string_escape(string &result, const char *str, const char *quote)
  46. {
  47. int length = (int) strlen(str);
  48. if (quote[0]) {
  49. result.append(1, quote[0]);
  50. }
  51. for (int i = 0; i < length; i++) {
  52. if (!isalnum((unsigned char) str[i])) {
  53. const char *const chars = "\n\t\\\r\"";
  54. const char *const special = strchr(chars, str[i]);
  55. if (special) {
  56. result.append(escape_chars[special - chars]);
  57. } else {
  58. result.append(1, str[i]);
  59. }
  60. } else {
  61. result.append(1, str[i]);
  62. }
  63. }
  64. result.append(1, quote[0]);
  65. }
  66. void String_parse::get_remainder(std::string &field)
  67. {
  68. field.clear();
  69. skip_space();
  70. int len = str->length() - pos;
  71. if ((len > 0) && ((*str)[len - 1] == '\n')) { // if str ends in newline,
  72. len--; // reduce length to ignore newline
  73. }
  74. field.insert(0, *str, pos, len);
  75. }