Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the best way to hardcode a multiple-line string?

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?

like image 415
colinfang Avatar asked Jan 29 '13 15:01

colinfang


People also ask

How do you write multiple lines on a string?

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.


2 Answers

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" 
like image 193
Kit Avatar answered Oct 19 '22 20:10

Kit


If you are under F# 3.0, triple-quoted strings may be the answer:

let x = """ myline1 myline2 myline3"""    
like image 27
bytebuster Avatar answered Oct 19 '22 18:10

bytebuster