Skip to content

Instantly share code, notes, and snippets.

@svagionitis
Created August 2, 2017 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svagionitis/e9d4f3bc7415a2d8e902d487c7ca2195 to your computer and use it in GitHub Desktop.
Save svagionitis/e9d4f3bc7415a2d8e902d487c7ca2195 to your computer and use it in GitHub Desktop.
A function to stringify the newline character.
/** @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