开发者

Newlines and formatters

I recently got bit by becoming complacent writing things like

printf "\n%f\n" 3.2

instead of

printf "%s%f%s" Environment.NewLine 3.2 Environment.NewLine

My question is: is there any way to write the safe second version as 开发者_运维问答nicely as the first (i.e. a special character in the format string which inserts Environment.Newline so that an argument for each newline instance in the format string isn't required)?


How about using kprintf for a double pass, replacing \n with NewLine:

let nprintf fmt = Printf.kprintf (fun s -> s.Replace("\n", Environment.NewLine) |> printf "%s") fmt

Then in nprintf "\n%f\n" 3.2 all \n get replaced by NewLine.


There's not an escape sequence, but you could shorten it:

[<AutoOpen>]
module StringFormatting =
    let nl = System.Environment.NewLine

//Usage
printfn "%s%f%s" nl 3.2 nl

Here is the list of character escapes on MSDN.

As an aside, I wonder what this would do:

printfn @"
%f
" 3.2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜