HOW TO:將字元寫入至字串

更新:2007 年 11 月

下列程式碼範例自字元陣列的指定位置開始,從陣列中寫入一定數目字元到現有字串。請使用 StringWriter,如下所示。

範例

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Imports System.Text
Public Class CharsToStr
    Public Shared Sub Main()
        ' Create an instance of StringBuilder that can then be modified.
        Dim sb As New StringBuilder("Some number of characters")
        ' Define and create an instance of a character array from which 
        ' characters will be read into the StringBuilder.
        Dim b As Char() = {" "c, "t"c, "o"c, " "c, "w"c, "r"c, "i"c, "t"c, "e"c, " "c, "t"c, "o"c, "."c}
        ' Create an instance of StringWriter 
        ' and attach it to the StringBuilder.
        Dim sw As New StringWriter(sb)
        ' Write three characters from the array into the StringBuilder.
        sw.Write(b, 0, 3)
        ' Display the output.
        Console.WriteLine(sb)
        ' Close the StringWriter.
        sw.Close()
    End Sub
End Class
using System;
using System.IO;
using System.Text;

public class CharsToStr
{
    public static void Main(String[] args)
    {
        // Create an instance of StringBuilder that can then be modified.
        StringBuilder sb = new StringBuilder("Some number of characters");
        // Define and create an instance of a character array from which 
        // characters will be read into the StringBuilder.
        char[] b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'};
        // Create an instance of StringWriter 
        // and attach it to the StringBuilder.
        StringWriter sw = new StringWriter(sb);
        // Write three characters from the array into the StringBuilder.
        sw.Write(b, 0, 3);
        // Display the output.
        Console.WriteLine(sb);
        // Close the StringWriter.
        sw.Close();
    }
}

穩固程式設計

這個範例說明如何使用 StringBuilder,以修改現有字串。注意,這需要額外的 using 宣告,因為 StringBuilder 類別是 System.Text 命名空間的成員。同樣的,這是直接建立並初始化字元陣列的範例,不需定義字串並轉換它為字元陣列。

這個程式碼產生下列輸出。

Some number of characters to

請參閱

工作

HOW TO:建立目錄清單

HOW TO:讀取和寫入新建立的資料檔案

HOW TO:開啟並附加至記錄檔

HOW TO:從檔案讀取文字

HOW TO:將文字寫入檔案

HOW TO:從字串中讀取字元

概念

基本檔案 I/O

參考

StringWriter

StringWriter.Write

StringBuilder