how to print string esc characters

P

Peted

Hi

im sending this string to a device
String cmd = ""N1\x0D")

this device needs the esc \x0D on the end where you see it

After i have sent this string i want to print it our to a rich
textbox, but the \x0D keeps performaing the CR
I dont want the CR to occur, i want the string to print the actual
\x0D letters.

How can i do this after i have sent the string as is to the device.
How to i convert it so the esc characters print ?


thanks for any help

Peted
 
N

Nicholas Paldino [.NET/C# MVP]

Peted,

You are going to have to look for the character code in the string and
then replace it with the literal "\x0D". Just call the replace function,
looking for a string with that value, and then replace it with the actual
string @"\x0D" (or \\x0D).
 
B

Ben Voigt

Hi

im sending this string to a device
String cmd = ""N1\x0D")

this device needs the esc \x0D on the end where you see it

After i have sent this string i want to print it our to a rich
textbox, but the \x0D keeps performaing the CR
I dont want the CR to occur, i want the string to print the actual
\x0D letters.

How can i do this after i have sent the string as is to the device.
How to i convert it so the esc characters print ?

Here's my version which I use for generating C# code (note not all cases are
tested), your string would become "\"N1\r". It should be easy enough to
remove the switch statement if you always want the hex code:

public static string EscapeLiteralString(string literal)
{
StringBuilder sb = new StringBuilder("\"", literal.Length + 2);
for (int index = 0; index < literal.Length; index++)
{
Char c = literal[index];
if (c < 32)
{
sb.Append('\\');
switch (c)
{
case '\0':
sb.Append('0');
break;
case '\a':
sb.Append('a');
break;
case '\b':
sb.Append('b');
break;
case '\f':
sb.Append('f');
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;
default:
sb.Append("x").Append(((UInt16)c).ToString("X02"));
break;
}
}
else if (c < 127)
{
if (c == '\"' || c == '\"' || c == '\\')
sb.Append('\\');
sb.Append(c);
}
else
{
int utf32 = Char.ConvertToUtf32(literal, index);
if (utf32 < 0x10000)
sb.Append("\\u").Append(utf32.ToString("X04"));
else
sb.Append("\\U").Append(utf32.ToString("X08"));
if (utf32 != c)
index++;
}
}
return sb.Append('\"').ToString();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top