Cómo: Escribir caracteres en una cadena

Actualización: noviembre 2007

En el siguiente ejemplo de código, se escribe un número específico de caracteres de una matriz de caracteres en una cadena existente, que comienza en un punto determinado de la matriz. Para ello, utilice StringWriter, tal y como se muestra a continuación.

Ejemplo

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Imports System.Text
Public Class CharsToStr
    Public Shared Sub Main()
        ' Create an instance of StringBuilder that can then be modified.
        Dim sb As New StringBuilder("Some number of characters")
        ' Define and create an instance of a character array from which 
        ' characters will be read into the StringBuilder.
        Dim b As Char() = {" "c, "t"c, "o"c, " "c, "w"c, "r"c, "i"c, "t"c, "e"c, " "c, "t"c, "o"c, "."c}
        ' Create an instance of StringWriter 
        ' and attach it to the StringBuilder.
        Dim sw As New StringWriter(sb)
        ' Write three characters from the array into the StringBuilder.
        sw.Write(b, 0, 3)
        ' Display the output.
        Console.WriteLine(sb)
        ' Close the StringWriter.
        sw.Close()
    End Sub
End Class
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.
        Console.WriteLine(sb);
        // Close the StringWriter.
        sw.Close();
    }
}

Programación eficaz

Este ejemplo muestra el uso de un StringBuilder para modificar una cadena existente. Tenga en cuenta que es necesaria una declaración using adicional, ya que la clase StringBuilder es miembro del espacio de nombres System.Text. Además, en lugar de definir una cadena y convertirla en matriz de caracteres, éste es un ejemplo de cómo crear una matriz de caracteres directamente e inicializarla.

Este código genera el siguiente resultado.

Some number of characters to

Vea también

Tareas

Cómo: Crear una lista de directorios

Cómo: Leer y escribir en un archivo de datos recién creado

Cómo: Abrir y anexar a un archivo de registro

Cómo: Leer texto de un archivo

Cómo: Escribir texto en un archivo

Cómo: Leer caracteres de una cadena

Conceptos

E/S de archivos básica

Referencia

StringWriter

StringWriter.Write

StringBuilder