How to do multiline strings?
I am wondering how can you do multi line strings without the concat sign(+)
I tried this
string a = String.Format(@"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
{0}xxxxxxx", "GGG");
string b = @"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
xxxxxxx";
string c = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
+ "xxxxxxx";
Cons开发者_Python百科ole.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
This works but the first 2 render alot of whitespace. Is there away to write multi lines without the concat sign and ignore end whitespace without using something like replace after the string is rendered?
Edit
using System; using
System.Collections.Generic; using
System.Linq; using System.Text;
namespace ConsoleApplication2 {
public class Test
{
public Test()
{
}
public void MyMethod()
{
string someLongString = "On top of an eager overhead weds a
pressed vat. How does a chance cage
the contract? The glance surprises the
radical wild.";
}
} }
Look how it goes right though my formating of the braces and is sticking out(sorry kinda hard to show on stack but it is sticking way to far out).
Sad thing is notepad++ does a better job and when it wraps it goes right under the variable.
Just remove the white space. It may not be pretty, but it works:
string a = @"this is the first line
and this is the second";
Note that the second line needs to go all the way to the left margin:
As an alternative, you can use the \n
character, but then you can't use verbatim strings (the @-prefix):
string a = "first line\nsecond line";
There's no form of string literal which allows multi-line strings but trims whitespace at the start of each line, no.
Any whitespace you include in the multiline string will always be included.
However ... try formatting your code like this:
string a = String.Format(
@"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
{0}xxxxxxx", "GGG");
... hopefully that looks better.
The solution is to enable Word Wrap when viewing code like this. That will both preserve the formatting and allow you to view the entire string wrapped without having to scroll in the editor.
You can do this by pressing Ctrl+e, W, or by selecting Edit/Advanced/Word Wrap from the menu.
You can do this while preserving code formatting, assuming the following:
- Regex is acceptable
- Your strings' whitespaces are always maximum 1 character long:
var words = Regex.Replace(
@"lorem ipsum dolor sit amet consectetur adipiscing
elit sed feugiat consectetur pellentesque nam ac
elit risusac blandit dui duis rutrum porta tortor ut
convallis duis rutrum porta tortor ut yth convallis
lorem ipsum dolorsit amet consectetur adipiscing elit
sed feugiat consectetur pellentesque nam ac elit
risus ac blandit dui duis rutrum porta tortor ut
convallis duis rutrum porta tortor ut convallis
", @"\s+", " ");
精彩评论