Procedura: leggere caratteri da una stringa

Aggiornamento: novembre 2007

Il codice dell'esempio che segue consente di leggere un determinato numero di caratteri da una stringa, a partire da un punto specifico. A tale scopo, viene utilizzato StringReader.

Il codice consente di definire una stringa e di convertirla in una matrice di caratteri, che può essere letta utilizzando il metodo StringReader.Read appropriato.

In questo esempio dalla stringa viene letto solo il numero di caratteri specificato, come indicato di seguito.

Some number o

Esempio

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Public Class CharsFromStr
    Public Shared Sub Main()
        ' Create a string to read characters from.
        Dim str As [String] = "Some number of characters"
        ' Size the array to hold all the characters of the string
        ' so that they are all accessible.
        Dim b(24) As Char
        ' Create an instance of StringReader and attach it to the string.
        Dim sr As New StringReader(str)
        ' Read 13 characters from the array that holds the string, starting
        ' from the first array member.
        sr.Read(b, 0, 13)
        ' Display the output.
        Console.WriteLine(b)
        ' Close the StringReader.
        sr.Close()
    End Sub
End Class
using System;
using System.IO;
public class CharsFromStr
{
    public static void Main(String[] args)
    {
        // Create a string to read characters from.
        String str = "Some number of characters";
        // Size the array to hold all the characters of the string
        // so that they are all accessible.
        char[] b = new char[24];
        // Create an instance of StringReader and attach it to the string.
        StringReader sr = new StringReader(str);
        // Read 13 characters from the array that holds the string, starting
        // from the first array member.
        sr.Read(b, 0, 13);
        // Display the output.
        Console.WriteLine(b);
        // Close the StringReader.
        sr.Close();
    }
}

Vedere anche

Attività

Procedura: creare una visualizzazione directory

Procedura: leggere e scrivere su un file di dati appena creato

Procedura: aprire e accodare un file di log

Procedura: leggere testo da un file

Procedura: scrivere testo su un file

Procedura: scrivere caratteri in una stringa

Concetti

I/O di file di base

Riferimenti

StringReader

StringReader.Read