public static string Escape(string s)
{
int charUpto = 0;
StringBuilder sb = new StringBuilder();
while (charUpto < s.Length)
{
int c = s[charUpto];
if (c == 0xa)
{
// Strangely, you cannot put \ u000A into Java
// sources (not in a comment nor a string
// constant)...:
sb.Append("\\n");
}
else if (c == 0xd)
{
// ... nor \ u000D:
sb.Append("\\r");
}
else if (c == '"')
{
sb.Append("\\\"");
}
else if (c == '\\')
{
sb.Append("\\\\");
}
else if (c >= 0x20 && c < 0x80)
{
sb.Append((char)c);
}
else
{
// TODO: we can make ascii easier to read if we
// don't escape...
sb.AppendFormat(CultureInfo.InvariantCulture, "\\u{0:x4}", c);
}
charUpto++;
}
return sb.ToString();
}