共用方式為


如何:將引號放入字串中 (Windows Forms)

您有時可能想要將引號 (" ") 放入文字字串中。 例如:

She said, "You deserve a treat!"

或者,您也可以使用 Quote 欄位做為常數。

將引號放入您的程式碼中的字串

  1. 在 Visual Basic 中,將兩個引號插入資料列中做為內嵌的引號。 在 Visual C# 和 Visual C++ 中,將逸出序列 \「 插入為內嵌引號。 例如,若要建立前置字串,請使用下列程式碼。

    Private Sub InsertQuote()  
       TextBox1.Text = "She said, ""You deserve a treat!"" "  
    End Sub  
    
    private void InsertQuote(){  
       textBox1.Text = "She said, \"You deserve a treat!\" ";  
    }  
    
    private:  
       void InsertQuote()  
       {  
          textBox1->Text = "She said, \"You deserve a treat!\" ";  
       }  
    

    -或-

  2. 針對引號插入 ASCII 或 Unicode 字元。 在 Visual Basic 中,使用 ASCII 字元 (34)。 在 Visual C# 中,使用 Unicode 字元 (\u0022)。

    Private Sub InsertAscii()  
       TextBox1.Text = "She said, " & Chr(34) & "You deserve a treat!" & Chr(34)  
    End Sub  
    
    private void InsertAscii(){  
       textBox1.Text = "She said, " + '\u0022' + "You deserve a treat!" + '\u0022';  
    }  
    

    注意

    在此範例中,您無法使用 \u0022,因為不能使用表明是基本字元集中字元的通用字元名稱。 否則,您會產生 c3851。 如需詳細資訊,請參閱編譯器錯誤 C3851

    -或-

  3. 您也可以定義字元的常數,並且在需要時使用它。

    Const quote As String = """"  
    TextBox1.Text = "She said, " & quote & "You deserve a treat!" & quote  
    
    const string quote = "\"";  
    textBox1.Text = "She said, " + quote +  "You deserve a treat!"+ quote ;  
    
    const String^ quote = "\"";  
    textBox1->Text = String::Concat("She said, ",  
       const_cast<String^>(quote), "You deserve a treat!",  
       const_cast<String^>(quote));  
    

另請參閱