ho fatto un commento sopra chiedendo perché il titolo è stato cambiato ad assumere Regex doveva essere usato.
Io personalmente provo a non usare Regex perché è lento. Regex è ottimo per schemi di stringhe complessi, ma se le sostituzioni di stringhe sono semplici e hai bisogno di prestazioni, cercherò di trovare un modo senza utilizzare Regex.
Ha unito una prova. Esecuzione di un milione di sostituzioni con Regex e metodi di stringa.
Regex ha 26,5 secondi per completare, metodi delle stringhe hanno 8 secondi per completare.
//Using Regex.
Regex r = new Regex(@"\b[Tt]he\b");
System.Diagnostics.Stopwatch stp = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
string str = "The man is old. The is the Good. Them is the bad.";
str = r.Replace(str, "@@");
}
stp.Stop();
Console.WriteLine(stp.Elapsed);
//Using String Methods.
stp = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
string str = "The man is old. The is the Good. Them is the bad.";
//Remove the The if the stirng starts with The.
if (str.StartsWith("The "))
{
str = str.Remove(0, "The ".Length);
str = str.Insert(0, "@@ ");
}
//Remove references The and the. We can probably
//assume a sentence will not end in the.
str = str.Replace(" The ", " @@ ");
str = str.Replace(" the ", " @@ ");
}
stp.Stop();
Console.WriteLine(stp.Elapsed);
Perché il titolo modificato per includere Regex? C'è più di un modo per fare la sostituzione del testo. Di solito cerco di evitare Regex perché è lento, quindi non penso che il titolo avrebbe dovuto essere modificato per includere la risposta "assunta". – Crispy
@ Chris Persichetti: Questo è abbastanza giusto; Ho rimosso "regex" dal titolo. (L'avevo aggiunto in base ai tag, ma "regex" a quanto pare non era comunque uno dei tag originali.) –