{love to code?}

September 19, 2007

Writing a long string in multiple lines – c#

Filed under: C# — navaneethkn @ 1:41 PM
Tags: ,

Writing a big string will always produce scrollbars in the editor. So it’s better to split it to multiple lines which is more easy to read. This post discusses the various methods that can be used to split big lines into multiple lines.

Check this big line.

string BigLine = "bla bla  bla bla  bla bla  bla bla
bla bla  bla bla  bla bla  bla bla ";

Writing a string as shown above will produce error. This can be rewritten like

string BigLine = @"bla bla  bla bla  bla bla  bla bla
bla bla  bla bla  bla bla  bla bla ";

Or

string</font> BigLine = "bla bla  bla bla  bla bla  bla bla " +
"bla bla  bla bla  bla bla  bla bla ";

I always prefer the second one. Because first one will not move the next line to the starting of first line. And more over it won’t be possible to write first method for the following type of string.

string BigLine = @"bla bla  bla bla  bla bla  bla bla
bla bla  bla bla  bla bla\"test\"  bla bla ";

In this I am escaping " by specifying \. But .NET editor will produce an error.

7 Comments »

  1. string BigLine = @”bla bla bla bla bla bla bla bla

    bla bla bla bla bla bla\”test\” bla bla “;

    You can escape ” by using “” (2 of them)

    Comment by sunny — September 4, 2008 @ 7:54 AM | Reply

  2. Hi Navaneeth,

    Thanks for ur this article,
    But I want to split a long string into multiple line because I want to Print them. As we know the wrapping cannot be done in Printing.

    Comment by Pavan kumar — February 16, 2009 @ 12:07 PM | Reply

  3. Thank you! I knew there was a way to do this, just couldn’t find it.

    Comment by AG — March 17, 2009 @ 8:57 PM | Reply

  4. Hi Naveenth,

    Thanks for sharing this usefull bit of information.

    Comment by Wajhi — June 11, 2009 @ 10:37 AM | Reply

  5. what can i do when one of the line is something like this

    “blaa= blaa.replace(‘/[\(\)\-\ ]/g’, ”);”+

    i got unrecognized escape sequence

    Comment by Mike — June 17, 2009 @ 1:14 AM | Reply

  6. Hi,how can I do this in vb.net?Someone help.Thanks.

    Comment by Suzan — November 12, 2009 @ 1:29 PM | Reply

  7. Ok,I got it…
    Just replace “+” with “& _”

    As in,

    Dim BigLine as string= “bla bla bla bla bla bla bla bla ” & _
    “bla bla bla bla bla bla bla bla “

    Comment by Suzan — November 12, 2009 @ 1:35 PM | Reply


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.