方法 : 文字列に文字を書き込む

更新 : 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 を使用して既存の文字列を変更する方法が示されています。StringBuilder クラスは System.Text 名前空間のメンバであるため、この操作を実行するには追加の using 宣言が必要です。また、この例では、文字列を定義してから文字配列に変換するのではなく、文字配列を直接作成して初期化しています。

このコードを実行すると、次の出力が生成されます。

Some number of characters to

参照

処理手順

方法 : ディレクトリ一覧を作成する

方法 : 新しく作成されたデータ ファイルに対して読み書きする

方法 : ログ ファイルを開いて情報を追加する

方法 : ファイルからテキストを読み取る

方法 : ファイルにテキストを書き込む

方法 : 文字列から文字を読み取る

概念

基本のファイル I/O

参照

StringWriter

StringWriter.Write

StringBuilder