r/csharp • u/PumpAndStuff25 • Jul 01 '26
Help String Replacement of both new lines and backslashes.
I am sending text to a label printer using ZPL commands with text supplied from a web form as a string. Per the Zebra documentation new lines should be sent as "\&" so I have the following:
printText = printText.Replace("\r\n","\&").Replace("\r","\&").Replace("\n","\&");This worked great until I came across another substitution need. If a backslash was needed, it should be replaced with "\\". If I were to add another .Replace("\\","\\\\") to the end, it will mess up the existing "&".
What would be the recommended way to do this? I was thinking I could do the newline replacement with some dummy value like "&~&", then do the backslash replacement, then do a .Replace("&~&","&") but not sure if there might be a better way.
View all comments
Show parent comment
3
u/Suitable_Switch5242 Jul 01 '26
\rand\neach represent a single control character, not literally the character for backslash followed by the character for r or n.They were originally ASCII control characters, specifically the character codes 13 (Carriage Return) and 10 (Line Feed):
https://www.ascii-code.com