Reading Characters from a String

The following code example allows you to read a certain number of characters from an existing string, starting at a specified place in the string. Use StringReader to do this, as demonstrated below.

This code defines a string and converts it to an array of characters, which can then be read by using the appropriate StringReader.Read method.

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();
    }
}

This example reads only the specified number of characters from the string, as follows.

Some number o

See Also

Creating a Directory Listing | Reading and Writing to a Newly Created Data File | Opening and Appending to a Log File | Reading Text from a File | Writing Text to a File | Writing Characters to a String | Basic File I/O | StringReader | StringReader.Read