Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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