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