Monday, 13 March 2017

string vs StringBuilder

The string class is an immutable class; what does that mean you ask, well mutable means "Liable to change" thus one could surmise that immutable classes are ones that can't change. Wait you've been concatenating strings since 1995, well guess what it's time to stop. Every time you you think you're combing two string you're actually creating a new one. Whenever you call replace, remove, or any other string function, you're not modifying the current string you're creating a new one.

using System;

class Program
{
    static void Main(string[] args)
    {
        string str1 = "133woot7";
        string str2 = str1.Remove(3, 4);

        Console.WriteLine(str1);
        Console.WriteLine(str2);
    }
}

as you can see in the above example, str1 doesn't change, it creates a new string in this case str2. If the string class is so poor at manipulating strings what's it for then, well displaying them of course.

the string class contains a readonly indexer that can be used to traverse each character in it.

static void Main(string[] args)
{
    var str1 = "hello world";

    foreach(char c in str1)
        Console.Write(c);

}

it also contains an instance property for the length of a string

static void Main(string[] args)
{
    var str1 = "hello world";

    foreach(char c in str1)
        Console.Write(c);

    Console.WriteLine();
    Console.WriteLine(str1.Length);

}

which will let us know how long a string is

the string class also have one static readonly property that represents an empty string.

var emptystring = String.Empty;

now it's accepted that when you're calling a static string function such as format you do it with the capital String and when your instantiating a string you use the lowercase string.

Now if you're going to concatenate string this is where you would use the StringBuilder class.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string[] Names = { "Pavel""Tomek""Marin""Ivan", };
        StringBuilder TheBoys = new StringBuilder();

        foreach (string name in Names)
            TheBoys.Append(name + Environment.NewLine);
       
        Console.WriteLine(TheBoys);
        Console.Read();
    }
}