如何在C#中创建带引号的字符串

6

我是一名 C# 新手。我想按如下方式设置一个 C# 变量。

string profileArg = @"/profile ""eScore"" ";

最终的结果是我希望变量包含这个值。
/profile "eScore" 

"eScore"后面的字符串需要加上一个空格。

我该怎么做?

Seth


5
我对你的问题感到困惑,string profileArg = @"/profile ""eScore"" "; 似乎正是你想要的。 - Bertrand Marron
也许你看不到尾随的空格,因为它是空的 :) - digEmAll
9个回答

13

你的字符串中,在 eScore 后面有一个空格。

// a space after "eScore"
string profileArg = @"/profile ""eScore"" ";

// no space after "eScore"
string profileArg = @"/profile ""eScore""";

// space in "eScore "
string profileArg = @"/profile ""eScore """;

// No space using escaping
string profileArg = "/profile \"eScore\"";

13

您似乎已经做得很正确了。


2
string profileArg = "/profile \"eScore\" ";

1
在逐字字符串中(@ 使其成为逐字字符串),反斜杠不用于转义,而是使用双引号 ""(就像 VB 一样)。 - Adam Ruth

1
string profileArg = "/profile \"eScore\" ";

1

2个选项:

  • 正常反斜杠转义:"This is a test of \"Quotes\"."
  • @字符串双重转义:@"This is a test of ""Quotes""."

这两个选项应该包含相同的字符串:

This is a test of "Quotes".

1

一个可能性是

string profileArg = "/profile \"eScore\" ";

对我来说,这比逐字逐句的文字更清晰


0

试试这个:

string profileArg = "/profile \"eScore\" ";

你想为任何双引号文字加上\"


对不起,我不是故意漏掉 @ 符号的。 - ItsPronounced

0
补充其他人的回答……在第一个引号前面加上@符号,可以告诉C#不要将反斜杠\解释为转义字符。这就是为什么给出的示例省略了@符号的原因。然后你可以使用\"来插入引号。

0

给你

String test = "   /profile \"eScore\"     ";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接