Is there a way in Visual Studio to convert text to a C# string literal and back?
For example if I have the text:
Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat.
开发者_开发知识库
can I easily convert it to:
"Lorem ipsum dolor sit amet, consectetuer adipiscing\n" +
"elit, sed diam nonummy nibh euismod tincidunt ut\n" +
"laoreet dolore magna aliquam erat volutpat."
and then convert it back using a macro or some utility?
You know you can do
@"Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat."
right? @-strings (a.k.a. "verbatim string literals") can contain newlines.
there are add ons for that take a look here http://arcanecode.com/2006/11/20/visual-studio-add-ins-paste-as/
In Visual Studio 2013, you can install 'SmartPaster2013' via Extensions and Updates.
If you prefix the string with an @ you can get something similar:
string lorem = @"Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat.";
This will preserve the whitespace.
DevExpress CodeRush can do this.
Yes. Use:
string s = @"Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat.
";
If you don't mind extra whitespace, you can enclose it in quotes and include the @
symbol at the beginning which means 'literal.' Like this:
string s = @"Lorem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat.";
If you are using Visual Studio, you can load the value into a variable and copy Value from Locals Window by double-clicking so it's highlighted as text
It's a little fidgety to do, but can be done.
Or you write a long tedious function like this one
static string ToCodeString(string s)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
char c;
int i = 0;
while (i < s.Length)
{
c = (char)s[i];
if (c == 34 || c == 92 || c == 93) //speechmarks backslash
{
sb.Append("\\" + c);
}
else if (c == 13)
{
sb.Append("\\r");
}
else if (c == 10)
{
sb.Append("\\n");
}
else if (c == 0)
{
sb.Append("\\0");
}
else if (c == 7)
{
sb.Append("\\a");
}
else if (c == 8)
{
sb.Append("\\b");
}
else if (c == 12)
{
sb.Append("\\f");
}
else if (c == 9)
{
sb.Append("\\t");
}
else if (c == 11)
{
sb.Append("\\v");
}
else if (c >= 32 && c <= 127) //ascii
{
sb.Append(c);
}
//else <-- if you want to represent unicode in ascii
//{
// sb.Append(string.Format(@"\u{0:x4}", (int)c));
//}
else
{
sb.Append(c);
}
i++;
}
return sb.ToString();
}
精彩评论