| String Tips and Tricks in C# |
|
Page 1 of 4 This is a beginner-level tutorial covering several String-related tips and tricks in C#, including immutability, concatenation, object nature, formatting, checking for empty, trimming, and escaping. Originally published on Published: Oct 24, 2006. Getting StartedBefore we get started, I've gotten a number of emails asking what programming books I recommend, and though a lot of the answer depends upon your specific experience, here are a few best-bets to get you started.
Strings are ImmutableStrings are immutable, which means that they cannot be changed in memory. So if you, for example, append something to a string, the .Net Framework will actually reserve memory for a new string of the total desired length and then copy the original string and the new string into it. So long as the original strings are still reference, they will not be garbage-collected. Concatenating StringsBecause strings are immutable, concatenating like the first example below is not advisable, although it will work. // AVOID this method. string s = "hello"; s += " there"; s += ", everyone"; // This is better. StringBuilder sb = new StringBuilder(23); // guess at the length sb.Append( "hello" ); sb.Append( " there" ); sb.Append( ", everyone" ); Console.WriteLine( sb.ToString() ); // Or this way... StringBuilder sb = new StringBuilder(23); // guess at the length sb.Append( "hello" ).Append( " there" ).Append( ", everyone" ); Console.WriteLine( sb.ToString() ); // Or best of all: String s = "hello there, everyone"; Notice that the StringBuilder takes an optional Int32 when it's constructed. (Above I used 23.) It's good practice to make a guess at the total length of the string you'll be creating, especially if you expect the end result to be a rather short string (less than 100 or so characters). This is because a StringBuilder, by default, initializes with a total string capacity of 16 bytes, and it's adjusted automatically (by doubling the capacity) if the string you're building exceeds this capacity. Adjusting this capacity takes the computer a little extra time, which means that it can actually be less efficient than the "avoid this" method above for short strings, unless you set the initial capacity when you construct it. |
|||||||

