www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to escape control characters?

reply cy <dlang verge.info.tm> writes:
This might be a dumb question. How do I format a string so that 
all the newlines print as \n and all the tabs as \t and such?
Mar 30 2016
parent reply Seb <seb wilzba.ch> writes:
On Thursday, 31 March 2016 at 03:15:49 UTC, cy wrote:
 This might be a dumb question. How do I format a string so that 
 all the newlines print as \n and all the tabs as \t and such?
http://dlang.org/spec/lex.html#WysiwygString r"ab\n" or `ab\n`
Mar 30 2016
next sibling parent reply "H. S. Teoh via Digitalmars-d-learn" <digitalmars-d-learn puremagic.com> writes:
On Thu, Mar 31, 2016 at 03:23:52AM +0000, Seb via Digitalmars-d-learn wrote:
 On Thursday, 31 March 2016 at 03:15:49 UTC, cy wrote:
This might be a dumb question. How do I format a string so that all
the newlines print as \n and all the tabs as \t and such?
http://dlang.org/spec/lex.html#WysiwygString r"ab\n" or `ab\n`
Or the verbose way: "abc\\ndef\\tghi" But if the string is only known at runtime, you'd probably have to use std.regex.replaceAll or something like that to manually escape characters. Or implement manual substitution with a pipeline: string myString = ...; string escapedStr = myString .chunks(1) .map!(c => (c == "\n") ? "\\n" : (c == "\r") ? "\\r" : (c == "\t") ? "\\t" : c) .joiner .array; T -- Береги платье снову, а здоровье смолоду.
Mar 30 2016
parent cy <dlang verge.info.tm> writes:
Oh, cool.

On Thursday, 31 March 2016 at 03:29:19 UTC, H. S. Teoh wrote:
 Or implement manual substitution with a pipeline:
 	string myString = ...;
 	string escapedStr = myString
 		.chunks(1)
 		.map!(c => (c == "\n") ? "\\n" :
 			   (c == "\r") ? "\\r" :
 			   (c == "\t") ? "\\t" :
 			   c)
 		.joiner
 		.array;
What I did was string escapedStr = myString .replace("\n",`\n`) .replace("\r",`\r`) .replace("\t",`\t`); That makes like 3 copies of the string I guess, but whatever. I'm not sure how efficient a general chunking filter would be on 1-byte chunks, and I certainly don't want to be creating a zillion unescaped 1-byte strings, so if I cared I'd probably do something like this: auto escapedStr = appender!string; for(c;myString) { switch(c) { case '\n': escapedStr.put("\\n"); case '\r': escapedStr.put("\\r"); ... default: escapedStr.put(c); } } It'd have to be long and boring to get all the control characters though, and possibly unicode ones too, or do "\xNN" style byte escapes. So I was hoping something standard already existed.
Mar 30 2016
prev sibling parent cy <dlang verge.info.tm> writes:
On Thursday, 31 March 2016 at 03:23:52 UTC, Seb wrote:
 http://dlang.org/spec/lex.html#WysiwygString

 r"ab\n" or `ab\n`
Yes I know. But I mean like, string a = r"ab\n"; writeln(escape(a)); // => ab\n
Mar 30 2016