.NET Framework 開發人員手冊
HOW TO:從字串中讀取字元

更新:2007 年 11 月

下列程式碼範例允許您自現有字串中的指定位置開始,從字串讀取一定數目的字元。請使用 StringReader,如下所示。

這個程式碼定義字串並將字串轉換成字元陣列,接著可使用適當的 StringReader..::.Read 方法讀取陣列。

這個範例只從字串中讀取指定的字元數,如下所示。

Some number o
範例

Visual Basic
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();
    }
}
請參閱

工作

概念

參考

標記 :


Page view tracker