In unit test I would like to hard code a block of lines as a string.
In C# I would do
var sb = new StringBuilder(); sb.AppendLine("myline1"); sb.AppendLine("myline2"); sb.AppendLine("myline3");
Since I converted to F# I tried to minimize the usage of .Net method by using bprintf
instead, but somehow there is no bprintfn
support which seems strange to me.
It is tedious to add \r\n
at the end of each line manually.
Or is there any better way than StringBuilder
?
Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
Little known feature: you can indeed indent string content - by ending each line with a backslash. Leading spaces on the following line are stripped:
let poem = "The lesser world was daubed\n\ By a colorist of modest skill\n\ A master limned you in the finest inks\n\ And with a fresh-cut quill.\n"
You will still need to include \n
or \n\r
at line ends though (as done in the example above), if you want these embedded in your final string.
Edit to answer @MiloDCs question:
To use with sprintf:
let buildPoem character = sprintf "The lesser world was daubed\n\ By a colorist of modest skill\n\ A master limned %s in the finest inks\n\ And with a fresh-cut quill.\n" character buildPoem "you" buildPoem "her" buildPoem "him"
If you are under F# 3.0, triple-quoted strings may be the answer:
let x = """ myline1 myline2 myline3"""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With