fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. /*
  6.  * Given a string which might contain unescaped newlines, split it up into
  7.  * lines which do not contain unescaped newlines, returned as a
  8.  * NULL-terminated array of malloc'd strings.
  9.  */
  10. char **split_on_unescaped_newlines(const char *txt) {
  11. const char *ptr, *lineStart;
  12. char **buf, **bptr;
  13. int fQuote, nLines;
  14.  
  15. /* First pass: count how many lines we will need */
  16. for ( nLines = 1, ptr = txt, fQuote = 0; *ptr; ptr++ ) {
  17. if ( fQuote ) {
  18. if ( *ptr == '\"' ) {
  19. if ( ptr[1] == '\"' ) {
  20. ptr++;
  21. continue;
  22. }
  23. fQuote = 0;
  24. }
  25. } else if ( *ptr == '\"' ) {
  26. fQuote = 1;
  27. } else if ( *ptr == '\n' ) {
  28. nLines++;
  29. }
  30. }
  31.  
  32. buf = malloc( sizeof(char*) * (nLines+1) );
  33.  
  34. if ( !buf ) {
  35. return NULL;
  36. }
  37.  
  38. /* Second pass: populate results */
  39. lineStart = txt;
  40. for ( bptr = buf, ptr = txt, fQuote = 0; ; ptr++ ) {
  41. if ( fQuote ) {
  42. if ( *ptr == '\"' ) {
  43. if ( ptr[1] == '\"' ) {
  44. ptr++;
  45. continue;
  46. }
  47. fQuote = 0;
  48. continue;
  49. } else if ( *ptr ) {
  50. continue;
  51. }
  52. }
  53.  
  54. if ( *ptr == '\"' ) {
  55. fQuote = 1;
  56. } else if ( *ptr == '\n' || !*ptr ) {
  57. size_t len = ptr - lineStart;
  58.  
  59. if ( len == 0 ) {
  60. *bptr = NULL;
  61. return buf;
  62. }
  63.  
  64. *bptr = malloc( len + 1 );
  65.  
  66. if ( !*bptr ) {
  67. for ( bptr--; bptr >= buf; bptr-- ) {
  68. free( *bptr );
  69. }
  70. free( buf );
  71. return NULL;
  72. }
  73.  
  74. memcpy( *bptr, lineStart, len );
  75. (*bptr)[len] = '\0';
  76.  
  77. if ( *ptr ) {
  78. lineStart = ptr + 1;
  79. bptr++;
  80. } else {
  81. bptr[1] = NULL;
  82. return buf;
  83. }
  84. }
  85. }
  86. }
  87.  
  88. int main(void) {
  89. // your code goes here
  90. char line[80] = "52,243,,542";
  91.  
  92. split_on_unescaped_newlines(line);
  93. printf("line %s\n", line[0]);
  94. printf("line %s\n", line[1]);
  95.  
  96. return 0;
  97. }
  98.  
Runtime error #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
Standard output is empty