This documentation is archived and is not being maintained.

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 namespace System;
using namespace System::IO;
using namespace System::Text;

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

int main()

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