How to: Read Characters from a String


The following code examples show how to read characters synchronously and asynchronously from a string.

This example reads 13 characters synchronously from a string, stores them in an array, and displays those characters. It then reads the remaining characters in the string, stores them in the array starting at the sixth element, and displays the contents of the array.

Imports System
Imports System.IO

Public Class CharsFromStr
    Public Shared Sub Main()
        Dim str As String = "Some number of characters"
        Dim b(str.Length) As Char

        Using sr As StringReader = New StringReader(str)
            ' Read 13 characters from the string into the array.
            sr.Read(b, 0, 13)

            ' Read the rest of the string starting at the current string position.
            ' Put in the array starting at the 6th array member.
            sr.Read(b, 5, str.Length - 13)
        End Using
    End Sub
End Class
' The example has the following output:
' Some number o
' Some f characters

The next example reads all the characters asynchronously from a TextBox control, and stores them in an array. It then asynchronously writes each letter or white space character on a separate line followed by a line break to a TextBlock control.

Imports System.IO
Imports System.Text

Class MainWindow

    Private Async Sub ReadButton_Click(sender As Object, e As RoutedEventArgs)
        Dim charsRead As Char() = New Char(UserInput.Text.Length) {}
        Using reader As StringReader = New StringReader(UserInput.Text)
            Await reader.ReadAsync(charsRead, 0, UserInput.Text.Length)
        End Using

        Dim reformattedText As StringBuilder = New StringBuilder()
        Using writer As StringWriter = New StringWriter(reformattedText)
            For Each c As Char In charsRead
                If Char.IsLetter(c) Or Char.IsWhiteSpace(c) Then
                    Await writer.WriteLineAsync(Char.ToLower(c))
                End If
        End Using
        Result.Text = reformattedText.ToString()
    End Sub
End Class

Asynchronous File I/O
NIB: How to: Create a Directory Listing
How to: Read and Write to a Newly Created Data File
How to: Open and Append to a Log File
How to: Read Text from a File
How to: Write Text to a File
How to: Write Characters to a String
File and Stream I-O