Partager via


Comment : écrire des caractères dans une chaîne

Mise à jour : novembre 2007

L'exemple de code suivant écrit un certain nombre de caractères à partir d'un tableau de caractères dans une chaîne existante, en commençant à un emplacement spécifié dans le tableau. Utilisez StringWriter à cette fin, comme illustré ci-dessous.

Exemple

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();
    }
}

Programmation fiable

Cet exemple illustre l'utilisation d'une classe StringBuilder pour modifier une chaîne existante. Notez que cette modification nécessite une déclaration using supplémentaire, étant donné que la classe StringBuilder est membre de l'espace de noms System.Text. Aussi, au lieu de définir une chaîne et de la convertir en tableau de caractères, cet exemple crée directement le tableau de caractères et l'initialise.

Ce code génère la sortie suivante :

Some number of characters to

Voir aussi

Tâches

Comment : créer une liste des répertoires

Comment : lire et écrire dans un fichier de données créé récemment

Comment : ouvrir un fichier journal et y ajouter des éléments

Comment : lire du texte dans un fichier

Comment : écrire du texte dans un fichier

Comment : lire les caractères d'une chaîne

Concepts

E/S de fichier de base

Référence

StringWriter

StringWriter.Write

StringBuilder