Share via


Procedura: modificare il contenuto delle stringhe (Guida per programmatori C#)

Poiché le stringhe sono non modificabili, non è possibile modificare il valore di un oggetto stringa dopo che è stato creato senza utilizzare codice unsafe. Ci sono tuttavia molti modi per modificare il valore di una stringa e archiviare il risultato in un nuovo oggetto stringa. La classe System.String fornisce metodi che operano su una stringa di input e restituiscono un nuovo oggetto stringa. In molti casi, è possibile assegnare il nuovo oggetto alla variabile che conteneva la stringa originale. La classe System.Text.RegularExpressions.Regex fornisce metodi aggiuntivi che funzionano in modo simile. La classe System.Text.StringBuilder fornisce un buffer di caratteri che è possibile modificare "sul posto". Il metodo StringBuilder.ToString viene chiamato per creare un nuovo oggetto stringa che contiene il contenuto corrente del buffer.

Esempio

Nell'esempio seguente vengono mostrati vari modi per sostituire o rimuovere sottostringhe in una stringa specifica.

class ReplaceSubstrings
{
    string searchFor;
    string replaceWith;

    static void Main(string[] args)
    {

        ReplaceSubstrings app = new ReplaceSubstrings();
        string s = "The mountains are behind the clouds today.";

        // Replace one substring with another with String.Replace.
        // Only exact matches are supported.
        s = s.Replace("mountains", "peaks");
        Console.WriteLine(s);
        // Output: The peaks are behind the clouds today.

        // Use Regex.Replace for more flexibility. 
        // Replace "the" or "The" with "many" or "Many".
        // using System.Text.RegularExpressions
        app.searchFor = "the"; // A very simple regular expression.
        app.replaceWith = "many";
        s = Regex.Replace(s, app.searchFor, app.ReplaceMatchCase, RegexOptions.IgnoreCase);
        Console.WriteLine(s);
        // Output: Many peaks are behind many clouds today.

        // Replace all occurrences of one char with another.
        s = s.Replace(' ', '_');
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_many_clouds_today.

        // Remove a substring from the middle of the string.
        string temp = "many_";
        int i = s.IndexOf(temp);
        if (i >= 0)
        {
            s = s.Remove(i, temp.Length);
        }
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_clouds_today.

        // Remove trailing and leading whitespace.
        // See also the TrimStart and TrimEnd methods.
        string s2 = "    I'm wider than I need to be.      ";
        // Store the results in a new string variable.
        temp = s2.Trim();
        Console.WriteLine(temp);
        // Output: I'm wider than I need to be.

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Custom match method called by Regex.Replace
    // using System.Text.RegularExpressions
    string ReplaceMatchCase(Match m)
    {
        // Test whether the match is capitalized
        if (Char.IsUpper(m.Value[0]) == true)
        {
            // Capitalize the replacement string
            // using System.Text;
            StringBuilder sb = new StringBuilder(replaceWith);
            sb[0] = (Char.ToUpper(sb[0]));
            return sb.ToString();
        }
        else
        {
            return replaceWith;
        }
    }
}

Per accedere ai singoli caratteri in una stringa tramite una notazione di matrice, è possibile utilizzare l'oggetto StringBuilder che esegue l'overload dell'operatore [] per fornire accesso al buffer di caratteri interno. È anche possibile convertire la stringa in una matrice di caratteri tramite il metodo ToCharArray. Nell'esempio seguente viene utilizzato ToCharArray per creare la matrice. Alcuni elementi di questa matrice vengono quindi modificati. Un costruttore di stringhe che accetta una matrice di caratteri come parametro di input viene quindi chiamato per creare una nuova stringa.

class ModifyStrings
{
    static void Main()
    {
        string str = "The quick brown fox jumped over the fence";
        System.Console.WriteLine(str);

        char[] chars = str.ToCharArray();
        int animalIndex = str.IndexOf("fox");
        if (animalIndex != -1)
        {
            chars[animalIndex++] = 'c';
            chars[animalIndex++] = 'a';
            chars[animalIndex] = 't';
        }

        string str2 = new string(chars);
        System.Console.WriteLine(str2);

        // Keep the console window open in debug mode
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
  The quick brown fox jumped over the fence
  The quick brown cat jumped over the fence 
*/

L'esempio seguente viene fornito per quelle situazioni molto rare nelle quali si potrebbe volere modificare una stringa sul posto tramite codice unsafe, in un modo simile alle matrici di caratteri di tipo C. Nell'esempio viene mostrato come accedere ai singoli caratteri "sul posto" tramite la parola chiave fixed. Viene inoltre mostrato un possibile effetto collaterale di operazioni non sicure sulle stringhe che risulta dalla modalità in cui il compilatore C# archivia (inserisce) stringhe all'interno. In generale, non è consigliabile utilizzare questa tecnica a meno che sia assolutamente necessario.

class UnsafeString
{
    unsafe static void Main(string[] args)
    {
        // Compiler will store (intern) 
        // these strings in same location.
        string s1 = "Hello";
        string s2 = "Hello";

        // Change one string using unsafe code.
        fixed (char* p = s1)
        {
            p[0] = 'C';
        }

        //  Both strings have changed.
        Console.WriteLine(s1);
        Console.WriteLine(s2);

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

Vedere anche

Concetti

Guida per programmatori C#

Stringhe (Guida per programmatori C#)