在字符串中包含引号?

Dun*_*mer 6 .net vb.net visual-studio

我试图在我的字符串中包含引号以添加到文本框,我正在使用此代码.

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

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

Dim Choice As String = "Your New Name is: NAME_HERE"
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 13

你必须逃避报价.在VB.NET中,您使用双引号 - "":

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

这将打印为:

Dim Choice1 As String = "Your New Name is: NAME HERE"
Run Code Online (Sandbox Code Playgroud)

假设count = 1(整数),则pt1 ="NAME",pt2 ="HERE".

如果count不是Integer,则可以删除ToString()调用.

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

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

哪个打印为:

string Choice1 = "Your new Name is: NAME HERE";
Run Code Online (Sandbox Code Playgroud)


Kon*_*lph 8

正如Tim所说,只需用"字符串替换字符串内的每一个匹配项"".

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

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

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

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