Created
September 10, 2013 17:23
-
-
Save cpq/6512657 to your computer and use it in GitHub Desktop.
Igor Izvarin's question on parsing string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage: | |
// cc -W -Wall ~/tmp/quoted_string_parser.c | |
// ./a.out " dwedewd, dede" " 'sds ee' ,'ddd'" | |
#include <stdio.h> | |
#include <string.h> | |
static const char *whitespaces = " \r\n"; | |
static const char *whitespaces_or_comma = " \r\n,"; | |
static const char *skip_to(const char *str, const char *to) { | |
return str + strcspn(str, to); | |
} | |
static const char *skip(const char *str, const char *chars) { | |
return str + strspn(str, chars); | |
} | |
static int word_len(const char *begin, const char *end) { | |
int len = end - begin; | |
return len > 0 && (begin[0] == '\'' || begin[0] == '"') ? len + 1 : len; | |
} | |
static const char *skip_word(const char *str, const char *until) { | |
char closing_quote[2] = { str[0], '\0' }; | |
return str[0] == '\'' || str[0] == '"' ? // word begins with quote? | |
skip_to(str + 1, closing_quote) : // yes, skip until closing quote | |
skip_to(str, until); // no, skip until first whitespace or comma | |
} | |
static void parse(const char *str) { | |
const char *a[5]; | |
a[0] = skip(str, whitespaces); // First word begin | |
a[1] = skip_word(a[0], whitespaces_or_comma); // First word end | |
a[2] = skip_to(a[1], ","); // Points to comma | |
a[3] = skip(a[2][0] == ',' ? a[2] + 1 : a[2], whitespaces); // Second word | |
a[4] = skip_word(a[3], whitespaces); // Second word end | |
printf("First: [%.*s] Second: [%.*s]\n", | |
word_len(a[0], a[1]), a[0], word_len(a[3], a[4]), a[3]); | |
} | |
int main(int argc, char *argv[]) { | |
int i; | |
for (i = 1; i < argc; i++) { | |
parse(argv[i]); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment