在字符串中包含引号?

时间:2011-08-30 07:22:14

标签: .net vb.net visual-studio

我正在尝试在字符串中添加引号以添加到文本框中,我正在使用此代码。

 t.AppendText("Dim Choice" & count + " As String = " + "Your New Name is:  & pt1 + "" & pt2 +" + vbNewLine)

但它不起作用,我希望它输出如下:

Dim Choice As String = "Your New Name is: NAME_HERE"

6 个答案:

答案 0 :(得分:13)

你必须逃避引号。在VB.NET中,您使用双引号 - “”:

t.AppendText("Dim Choice" + count.ToString() + " As String = ""Your New Name is: "  + pt1 + " " + pt2 + """" + vbNewLine)

这将打印为:

Dim Choice1 As String = "Your New Name is: NAME HERE"

假设count = 1(整数),pt1 =“NAME”,pt2 =“HERE”。

如果count不是整数,则可以删除ToString()调用。

在C#中,你通过使用\来逃避“,就像这样:

t.AppendText("string Choice" + count.ToString() + " = \"Your New Name is: " + pt1 + " " + pt2 + "\"\n");

将打印为:

string Choice1 = "Your new Name is: NAME HERE";

答案 1 :(得分:8)

正如蒂姆所说,只需用"替换字符串中的每个""

此外,使用String.Format使代码更具可读性:

t.AppendText( _
    String.Format( _
        "Dim Choice{0} As String = ""Your New Name is: {1} {2}""{3}", _
        count, pt1, pt2, vbNewLine)

根据t的类型,甚至可能有一种方法直接支持格式字符串,也许您甚至可以将上述内容简化为以下内容:

t.AppendText( _
    "Dim Choice{0} As String = ""Your New Name is: {1} {2}""{3}", _
    count, pt1, pt2, vbNewLine)

答案 2 :(得分:0)

你必须逃避它们,但是当你试图在这里时,你无法动态生成变量名:

"Dim Choice" & count + " As String = "

这只是一个字符串。

答案 3 :(得分:0)

您可以使用Chr Functionquotes ASCII Code:34来获得结果:

t.Append(Dim Choice As String = " & Chr(34) & "Your New Name is: NAME_HERE" & Chr(34))

答案 4 :(得分:0)

虽然转义字符串是正确的处理方式,但并不总是最容易阅读。考虑尝试创建以下字符串:

Blank "" Full "Full" and another Blank ""

要逃避这一点,您需要执行以下操作:

"Blank """" Full ""Full"" and another Blank """""

但如果您将String.FormatChr(34)一起使用,则可以执行以下操作:

String.Format("Blank {0}{0} Full {0}Full{0} and another Blank {0}{0}", Chr(34))

如果您觉得这更容易阅读,这是一个选项。

答案 5 :(得分:0)

VB .Net中你可以这样做:

假设count = 1 (Integer), pt1 = "NAME" and pt2 = "HERE"

t.AppendText("Dim Choice" & count.Tostring() + " As String ="+ CHR(34) + "Your New Name is: " & pt1 + "_" & pt2 +CHR(34) + vbNewLine)

输出将是 Dim Choice As String ="您的新名称是:NAME_HERE"

相关问题