Include quote marks inside a string?

2020-04-05 08:54发布

I'm trying to include quotes into my string to add to a text box, i am using this code.

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

but it doesnt work, i want it to output like so:

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

6条回答
Root(大扎)
2楼-- · 2020-04-05 09:29

In VB .Net you can do this :

Assuming 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)

The output will be Dim Choice As String = "Your New Name is: NAME_HERE"

查看更多
ら.Afraid
3楼-- · 2020-04-05 09:34

As Tim said, simply replace each occurrence of " inside the string with "".

Furthermore, use String.Format to make the code more readable:

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

Depending on the type of your t, there might even be a method that supports format strings directly, i.e. perhaps you can even simplify the above to the following:

t.AppendText( _
    "Dim Choice{0} As String = ""Your New Name is: {1} {2}""{3}", _
    count, pt1, pt2, vbNewLine)
查看更多
女痞
4楼-- · 2020-04-05 09:38

You have to escape the quotes. In VB.NET, you use double quotes - "":

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

This would print as:

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

Assuming count = 1 (Integer), pt1 = "NAME" and pt2 = "HERE".

If count is not an Integer, you can drop the ToString() call.

In C#, you escape the " by using a \, like this:

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

Which would print as:

string Choice1 = "Your new Name is: NAME HERE";
查看更多
▲ chillily
5楼-- · 2020-04-05 09:39

Although escaping the string is the correct way of doing things it is not always the easiest to read. Consider trying to create the following string:

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

To escape this you need to do the following:

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

But if you using String.Format with Chr(34) you can do the following:

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

This is an option if you find this easier to read.

查看更多
看我几分像从前
6楼-- · 2020-04-05 09:41

You have to escape them, however you cannot dynamically generate variable names as you're attempting to here:

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

this will just be a string.

查看更多
Explosion°爆炸
7楼-- · 2020-04-05 09:49

You can use the Chr Function with the quotes ASCII Code: 34 to have a result as this:

t.Append(Dim Choice As String = " & Chr(34) & "Your New Name is: NAME_HERE" & Chr(34))
查看更多
登录 后发表回答