Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

How to: Write Characters to a String

The following code examples write characters synchronously and asynchronously from a character array into a string.

The following example writes 5 characters synchronously from an array to a string.

Imports System
Imports System.IO
Imports System.Text

Public Class CharsToStr
    Public Shared Sub Main()
        Dim sb As New StringBuilder("Start with a string and add from ")
        Dim b() As Char = { "c", "h", "a", "r", ".", " ", "B", "u", "t", " ", "n", "o", "t", " ", "a", "l", "l" }

        Using sw As StringWriter = New StringWriter(sb)
            ' Write five characters from the array into the StringBuilder.
            sw.Write(b, 0, 5)
        End Using 
    End Sub 
End Class 
' The example has the following output: 

' Start with a string and add from char.

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
© 2015 Microsoft