Sunday, April 18, 2010

String replacement with Regular Expressions

I answered a question last week on a forum about using Regular Expressions for complex string replacements so I thought I might just post a small example. For simple string replacement there’s the String.Replace method, but whenever you need to manipulate the match you want to replace in order to build the replacement string, the RegEx.Replace method does the job. Here’s a small code sample that searches in a string for a parameter named “username” and its value and then builds a HTML link stirng with it.

private void button1_Click(object sender, EventArgs e)
{
 string s = "username=myusername";
 Regex patern = new Regex(@"\[(username=(\W+))\]");
 MatchEvaluator matchEval = new MatchEvaluator(GetReplacement);

 s = patern.Replace(s,GetReplacement);

 MessageBox.Show(s);

}
 
private string GetReplacement(Match m)
{
 return "" + m.Groups[2] + "";
} 

Sunday, April 4, 2010

Using the StringBuilder class

In .NET I often see people use the plus ‘+’ operator in C# or the ampersand ‘&’ operator in VB.NET to concatenate strings. Whenever these operators are use for concatenation the Framework copies all the strings included in the operation into memory and then reads back those value as a new string. This, even if it doesn’t seem to be, is a costly operation. This is where the StringBuilder comes in. This class, as MSDN describes it is “ a string-like object whose value is a mutable sequence of characters. The value is said to be mutable because it can be modified once it has been created by appending, removing, replacing, or inserting characters.” And the important thing to know is that it is faster than using concatenation operators as you can see in the following example.



using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Concatenation using string class and operators");
            string s = string.Empty;
            Console.WriteLine("Operation start time: " + DateTime.Now.ToLongTimeString());
            for (int i = 0; i < 100000; i++)
            {
                s += i.ToString();
            }
            Console.WriteLine("Operation stop time: " + DateTime.Now.ToLongTimeString());

            Console.WriteLine();

            Console.WriteLine("Concatenation using StringBuilder");
            StringBuilder sb = new StringBuilder(string.Empty);
            Console.WriteLine("Operation start time: " + DateTime.Now.ToLongTimeString());
            for (int i = 0; i < 100000; i++)
            {
                sb.Append(i);
            }
            Console.WriteLine("Operation stop time: " + DateTime.Now.ToLongTimeString());

            Console.WriteLine();
            Console.WriteLine("Press any key to close this window.");
            Console.ReadLine();
        }
    }
}







Sure if you only concatenate a couple of strings you won’t see the difference but still, I think that using the StringBuilder class whenever you need to manipulate a string is a good habit to take.