Skip to content

Instantly share code, notes, and snippets.

@cwchentw
Last active February 9, 2019 07:12
Show Gist options
  • Save cwchentw/67a1b491d65aa599c84b4f41513f5de3 to your computer and use it in GitHub Desktop.
Save cwchentw/67a1b491d65aa599c84b4f41513f5de3 to your computer and use it in GitHub Desktop.
Home-made mini separator interpreter (Apache 2.0)
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * separator_parse(const char *sep);
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "No valid argument\n");
return 1;
}
char *sep = separator_parse(argv[1]);
printf("-->%s<--\n", sep);
free(sep);
return 0;
}
char * separator_parse(const char *sep)
{
size_t size = strlen(sep);
char *out = malloc((size + 1) * sizeof(char));
size_t i = 0;
size_t j = 0;
while (j < size) {
if (sep[j] == '\\') {
// Last char in the sep string.
if (j + 1 >= size) {
out[i] = sep[j];
break;
}
switch (sep[j+1]) {
case '\\':
out[i] = '\\';
j++;
break;
case '\'':
out[i] = '\'';
j++;
break;
case '\"':
out[i] = '\"';
j++;
break;
case 'n':
out[i] = '\n';
j++;
break;
case 't':
out[i] = '\t';
j++;
break;
default:
out[i] = sep[j];
break;
}
}
else {
out[i] = sep[j];
}
i++; j++;
}
out[i+1] = '\0';
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment