Skip to content

Instantly share code, notes, and snippets.

@sinairv
Created May 14, 2012 13:38
Show Gist options
  • Save sinairv/2694034 to your computer and use it in GitHub Desktop.
Save sinairv/2694034 to your computer and use it in GitHub Desktop.
Representing strings with all their characters visible
/// <summary>
/// Returns a visible version of the string, by making
/// its whitespace and control characters visible
/// using well known escape sequences, or the equivalant
/// hexa decimal value.
/// </summary>
/// <param name="str">The string to be made visible.</param>
/// <returns></returns>
public static string MakeStringVisible(string str)
{
if (str == null)
return "{null}";
StringBuilder sb = new StringBuilder();
foreach (char ch in str)
{
if (Char.IsControl(ch) || Char.IsWhiteSpace(ch))
{
switch (ch)
{
case '\a':
sb.Append("\\a");
break;
case ' ':
sb.Append("\\s");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\v':
sb.Append("\\v");
break;
case '\f':
sb.Append("\\f");
break;
default:
sb.AppendFormat("\\u{0:X};", (int)ch);
break;
}
}
else
{
sb.Append(ch);
}
}
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment