|
Dit artikel is gepubliceerd op zondag 31 juli 2011 op vbvoorbeelden, bezoek de website voor een recente versie van dit artikel of andere artikels.
Elke String-manipulatie leidt tot de creatie van een nieuwe String instantie. Visual Basic 2010 Broncode Option Explicit OnOption Strict OnClass Example1 Public Shared Sub Main() Dim text1 As String = "abc" Dim text2 As String = text1 Console.WriteLine(text1 Is text2) text1 = text1 & "d" Console.WriteLine(text1 Is text2) Console.ReadLine() End SubEnd ClassDownload Visual Basic 2010 Broncode Download Visual C# Sourcecode
Console Application Output True
False 16.5.1. System.Text.StringBuilderIndien vele manipulaties, bijvoorbeeld toevoegingen, aan een tekst noodzakelijk zijn, is het beter hiervoor het immutable String type te vermijden. Bij deze zou immers elke manipulatie, leiden tot het instantiëren van een nieuw object, wat niet bepaald intressant is voor de performantie.
Een System.Text.StringBuilder biedt hier een oplossing. In dit type zijn tal van members gedefinieerd, die je toelaten een tekst te manipuleren, zonder dat hierbij steeds nieuwe instanties worden gemaakt. Visual Basic 2010 Broncode Class Example2 Public Shared Sub Main() Dim text As New System.Text. StringBuilder( "text") Console.WriteLine( text.Chars(3)) Console.WriteLine( text.Length) text = text.Append( "text") Console.WriteLine( text) Console.WriteLine( text.ToString()) Console.WriteLine( text.ToString(1, 3)) text = text.Append( New Char() { "a"c, "b"c, "c"c}) Console.WriteLine( text) text = text.Insert(4, "TEXT") Console.WriteLine( text) text = text.Insert(4, New Char() { "a"c, "b"c, "c"c}) Console.WriteLine( text) text = text.Remove(4, 7) Console.WriteLine( text) text = text.Replace( "text", "abc") Console.WriteLine( text) text = text.Replace( "b"c, "z"c) Console.WriteLine( text) Console.ReadLine() End SubEnd ClassDownload Visual Basic 2010 Broncode Download Visual C# Sourcecode
Console Application Output t
4
texttext
texttext
ext
texttextabc
textTEXTtextabc
textabcTEXTtextabc
texttextabc
abcabcabc
azcazcazc
Dit artikel is gepubliceerd op zondag 31 juli 2011 op vbvoorbeelden, bezoek de website voor een recente versie van dit artikel of andere artikels.
|