Created
August 2, 2017 12:14
-
-
Save svagionitis/e9d4f3bc7415a2d8e902d487c7ca2195 to your computer and use it in GitHub Desktop.
A function to stringify the newline character.
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
/** @brief Stringify the newline character of a string. | |
* | |
* In detail, the newline character, '\n' is not supported on | |
* json string, so it needs to split in two characters "\n". | |
* | |
* @param [in] src The string to stringify | |
* @return the stringified string on success<br> | |
* NULL otherwise | |
* | |
*/ | |
static char * | |
stringify_newline (char *src) | |
{ | |
char *dst, *str; | |
size_t count_newline = 0; | |
size_t src_sz, dst_sz, i, j; | |
if (!src) | |
return NULL; | |
src_sz = strlen (src); | |
/* count newline characters */ | |
for (str = src; *str != '\0'; str++) | |
if (*str == '\n') count_newline++; | |
dst_sz = src_sz + count_newline + 1; | |
dst = malloc (dst_sz); | |
if (!dst) | |
return NULL; | |
for (i = 0, j = 0; i < src_sz; i++) { | |
if (src[i] == '\n') { | |
dst[j++] = '\\'; | |
dst[j++] = 'n'; | |
} else | |
dst[j++] = src[i]; | |
} | |
dst[j] = '\0'; | |
return dst; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment