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
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Write Characters to a String 

The following code example writes a certain number of characters from a character array into an existing string, starting at a specified place in the array. Use StringWriter to do this, as demonstrated below.


using System;
using System.IO;
using System.Text;

public class CharsToStr
    public static void Main(String[] args)
        // Create an instance of StringBuilder that can then be modified.
        StringBuilder sb = new StringBuilder("Some number of characters");
        // Define and create an instance of a character array from which 
        // characters will be read into the StringBuilder.
        char[] b = {' ','t','o',' ','w','r','i','t','e',' ','t','o','.'};
        // Create an instance of StringWriter 
        // and attach it to the StringBuilder.
        StringWriter sw = new StringWriter(sb);
        // Write three characters from the array into the StringBuilder.
        sw.Write(b, 0, 3);
        // Display the output.
        // Close the StringWriter.

Robust Programming

This example illustrates the use of a StringBuilder to modify an existing string. Note that this requires an additional using declaration, since the StringBuilder class is a member of the System.Text namespace. Also, instead of defining a string and converting it to a character array, this is an example of creating a character array directly and initializing it.

This code produces the following output.

Some number of characters to

See Also

Community Additions

© 2015 Microsoft