2011-08-30 130 views
6

我想包括引號到我的字符串添加到文本框中,我使用此代碼。在字符串中包含引號?

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

,但它不工作,我希望它輸出像這樣:

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

回答

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" 

假設數= 1(整數),PT1 = 「名稱」 和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"; 
+0

上的代碼「」最後一位「+ vbNewLine)有錯:」字符串常量必須結束用雙引號「 –

+0

我更新了代碼的結尾以使用4」 - 即「」「」。我最初偶然發現了三個。對困惑感到抱歉。 – Tim

0

你要逃避他們,但你不能動態地產生變量名稱作爲你試圖在這裏:

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

這將只是一個字符串

+0

我不認爲OP試圖動態生成變量名稱,因爲他說他試圖將字符串放在TextBox中。 – Tim

+0

啊還不夠公平 –

0

您可以使用Chr Functionquotes ASCII Code:34有一個結果,因爲這:

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

不要在這裏使用'Chr',它只是使它不易讀。沒有人會在C#中使用'(char)34',你會使用'\「'。在VB中也是這樣。 –

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) 
+1

對於String.Format,我是代碼可讀性的忠實粉絲(儘管我保持忘記String.Format等簡單的東西...也許我會在長大的時候把它弄掉:))。 – Tim

0

雖然逃脫字符串是做事的正確方式它並不總是最容易閱讀。考慮嘗試創建以下字符串:如果您在使用String.FormatChr(34)你可以做以下

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

但是:

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

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

爲了避開這一點,你需要做以下

這是一個選項,如果你覺得這更容易閱讀。

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) 

輸出將是 昏暗選擇的String =「你的姓名是:NAME_HERE」

相關問題