次の方法で共有


文字列からの文字の読み取り

既存の文字列内の指定された位置から一定数の文字を読み取るコードの例を次に示します。この処理を行うには、次の例で示すように StringReader を使用します。

このコードでは、文字列を定義し、その文字列を文字の配列に変換します。この文字配列は、適切な StringReader.Read メソッドを使用することで読み取ることができます。

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Public Class CharsFromStr
    Public Shared Sub Main()
        ' Create a string to read characters from.
        Dim str As [String] = "Some number of characters"
        ' Size the array to hold all the characters of the string
        ' so that they are all accessible.
        Dim b(24) As Char
        ' Create an instance of StringReader and attach it to the string.
        Dim sr As New StringReader(str)
        ' Read 13 characters from the array that holds the string, starting
        ' from the first array member.
        sr.Read(b, 0, 13)
        ' Display the output.
        Console.WriteLine(b)
        ' Close the StringReader.
        sr.Close()
    End Sub
End Class

[C#]
using System;
using System.IO;
public class CharsFromStr
{
    public static void Main(String[] args)
    {
        // Create a string to read characters from.
        String str = "Some number of characters";
        // Size the array to hold all the characters of the string
        // so that they are all accessible.
        char[] b = new char[24];
        // Create an instance of StringReader and attach it to the string.
        StringReader sr = new StringReader(str);
        // Read 13 characters from the array that holds the string, starting
        // from the first array member.
        sr.Read(b, 0, 13);
        // Display the output.
        Console.WriteLine(b);
        // Close the StringReader.
        sr.Close();
    }
}

この例では、文字列から指定した数の文字 (つまり、次に示す文字) が読み取られます。

Some number o

参照

ディレクトリ一覧の作成 | 新しく作成したデータ ファイルの読み取りと書き込み | ログ ファイルのオープンと追加 | ファイルからのテキストの読み取り | ファイルへのテキストの書き込み | 文字列への文字の書き込み | 基本のファイル I/O | StringReader クラス | Read メソッド