Scrittura di caratteri in una stringa

Il codice dell'esempio che segue scrive in una stringa esistente un determinato numero di caratteri contenuti in una matrice di caratteri, a partire da un punto specifico della matrice. A tal fine, viene utilizzato StringWriter.

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

[C#]
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();
    }
}

Nell'esempio viene illustrato come utilizzare uno StringBuilder per modificare una stringa esistente. Si noti che questo richiede un'ulteriore dichiarazione using, perché la classe StringBuilder è un membro dello spazio dei nomi System.Text. Anziché definire una stringa e convertirla in una matrice di caratteri, in questo esempio viene inoltre creata direttamente e inizializzata una matrice di caratteri.

Il codice produce il seguente output:

Some number of characters to

Vedere anche

Creazione di un elenco di directory | Lettura e scrittura in un nuovo file di dati | Apertura e aggiunta a un file di log | Lettura di testo da un file | Scrittura di testo in un file | Lettura di caratteri da una stringa | I/O di file di base | StringWriter | StringWriter.Write | StringBuilder