escapeControlCharacters

Replaces the control characters '\n', '\t', '\r' and '\0' with the escaped "\\n", "\\t", "\\r" and "\\0". Does not allocate a new string if there was nothing to escape.

@safe pure nothrow
string
escapeControlCharacters
(
return scope string line
)

Parameters

line string

String line to escape characters in.

Return Value

Type: string

A new string with control characters escaped, or the original one unchanged.

Examples

{
    immutable line = "abc\ndef";
    immutable expected = "abc\\ndef";
    immutable actual = escapeControlCharacters(line);
    assert((actual == expected), actual);
}
{
    immutable line = "\n\t\r\0";
    immutable expected = "\\n\\t\\r\\0";
    immutable actual = escapeControlCharacters(line);
    assert((actual == expected), actual);
}
{
    immutable line = "";
    immutable expected = "";
    immutable actual = escapeControlCharacters(line);
    assert((actual == expected), actual);
    assert(actual is line);  // No string allocated
}
{
    immutable line = "nothing to escape";
    immutable expected = "nothing to escape";
    immutable actual = escapeControlCharacters(line);
    assert((actual == expected), actual);
    assert(actual is line);  // No string allocated
}

Meta