Friday, October 11, 2013

C# - Working with the String Builder class

Overview

The String builder class allows us to manipulate strings without affecting the memory allocation while running the application. To use a “String Builder” you first need to initialize a new instance of the class, using one of the following options: 


Option 1: Creating instance and initialize it with a default value
static void Main(string[] args)
        {
         StringBuilder example = new StringBuilder("The String value");           
        }

As you can see, we created a new sting using a string builder which equals to:

String example1 = "The String value ";

Option 2: Creating instance without initialization

StringBuilder EmptyString = new StringBuilder();
           
Option 3: Creating an instance with expected string length
You can specify the size of the expected string, by specifying it you can reduce the default memory allocation when declaring the new builder.

StringBuilder ExpectedLength = new StringBuilder(100);

Builder Properties and Methods

Like the ‘string’ class, the builder class uncovers few methods and properties that can be used while manipulating the initialized string, the next few examples will demonstrate how to achieve the best from them.

Append, AppendLine and AppendFormat methods
This three methods allow you to add additional syntax to initialized builder, the following example demonstrate how to use thus methods.

Example 1:
Append – add syntax without moving to next line

static void Main(string[] args)
        {
            StringBuilder PhoneNumber = new StringBuilder("My Name is : ");
            //Adding values directly (Option 1)

            PhoneNumber.Append("David\n");  
            PhoneNumber.Append("My Phone number: ");

            //Adding values using loop (Option 2)

            for (int i = 0; i < 9; i++)
            {
                PhoneNumber.Append(i);               
            }
            Console.WriteLine(PhoneNumber);
        }
    }

Result:
My Name is: David
My Phone number: 012345678

Example 2:
Append Line – Add syntax and start a new line

class Program
    {
        static void Main(string[] args)
        {
          StringBuilder PhoneNumber = new StringBuilder("My Name is : ");

            //Adding values directly (Option 1)

            PhoneNumber.AppendLine("David");  
            PhoneNumber.AppendLine("My Phone number: ");

            //Adding values using loop (Option 2)

            for (int i = 0; i < 9; i++)
            {
                PhoneNumber.Append(i);               
            }
            Console.WriteLine(PhoneNumber);
        }
    }

Result:
My Name is: David
My Phone number: 012345678

Example 3:
AppendFormat – this method allows you to modify specific values in your builder, as a result the code become much clearer for reading.

class Program
    {
        static void Main(string[] args)
        {   
            string BestMovieEver = "Rambo 2" ;
            string BestTvShow = "Oz";       

            StringBuilder FormatBuilder = new StringBuilder();
            FormatBuilder.AppendFormat
            (@"{0} is the Best Movie Ever!!!
            {1} is the best Tv Show", BestMovieEver,BestTvShow);
            Console.WriteLine(FormatBuilder);
        }
    }

Result:
Rambo 2 is the Best Movie Ever!!!
Oz is the best Tv Show!!!

Replace method
The ‘Replace’ method allow you to change values in specific string, the value can be simple char or long string (just like the ‘String’ class).

Note!
The only thing you must remember that this method will replace all instances and not a specific one.

class Program
    {
        static void Main(string[] args)
        {
            //Example 1:
            StringBuilder ReplaceValue = new StringBuilder("My name is : None");
            ReplaceValue.Replace("None" ,"David .T.");
            Console.WriteLine("Example 1 : " + ReplaceValue);

            //Example 2:
            StringBuilder ReplaceMultipleValues = new StringBuilder("0-1-0-1-0-1-0");

            ReplaceMultipleValues.Replace("0", "2");

            Console.WriteLine("Example 2 : " + ReplaceMultipleValues);        

        }

    }

Result:

Example 1: My name is: David .T.

Example 2: 2-1-2-1-2-1-2

Builder as ‘Char’ array
Like the sting object, the string builder is construct from a ‘Char’ array

 class Program
    {
        static void Main(string[] args)
        {
            StringBuilder CharsArray = new StringBuilder("aD");    

            //using builder as char array

            Console.WriteLine("Example 1:");

            Console.WriteLine("Changing specific char to Upper : " + char.ToUpper(CharsArray[0])); //Change single char to Upper case(a -> A)

            Console.WriteLine("Changing specific char to Lowe : " + char.ToLower(CharsArray[1])); //Change single char to Lower case(D -> d)                       

            //Moving builder into char array

            char[] CA = new char[CharsArray.Length];
            for (int i = 0; i < CA.Length; i++)
            {               
                CA[i] = CharsArray[i];                  
            }
            Console.WriteLine("\nExample 2:");
            foreach (var item in CA)
            {
                Console.Write(item);
            }
            Console.WriteLine();
        }
    }

 Result:

Example 1:
Changing specific char to Upper: A
Changing specific char to lower: d

Example 2:
aD

Clear method
The ‘Clear’ method will remove all data from a builder.
  class Program 
    {
        static void Main(string[] args)
        {
            StringBuilder clearvalues = new StringBuilder("1984");
            Console.WriteLine("Before : " + clearvalues);
            clearvalues.Clear();
            Console.WriteLine("After : " + clearvalues);
        }
    }

 Result:
Before: 1984
After:

Remove method
This method allow you to remove specific range of characters based on builder indexes.

class Program
    {
        static void Main(string[] args)
        {
            StringBuilder Remove = new StringBuilder("123456789");
            Console.WriteLine("Before : " + Remove);
            Remove.Remove(6,2);

            //Starting the removal from index 6
            //Remove 2 characters from index 6

            Console.WriteLine("After : " + Remove);
        }
    }

Result:
Before: 123456789
After: 1234569

Working with specific indexer
As explained, string builder construct from single chars, therefore we can use this issue to manipulate specific chars inside the builder.

class Program
    {
        static void Main(string[] args)
        {
            //Step 1: Creating builder
            StringBuilder changebyindexer = new StringBuilder("ABCD");

            //Step 2: Printing builder based on indexer
            Console.WriteLine("Original Builder : ");
            PrintingValues(changebyindexer);

            //Step 3:Changing value for indexer 2 and 4
            changebyindexer[1] = '1';
            changebyindexer[3] = '2';

            //Step 4: Printing builder after modification
            Console.WriteLine("Builder after modification : ");
            PrintingValues(changebyindexer);
        }

        private static void PrintingValues(StringBuilder changebyindexer)
        {
            for (int i = 0; i < changebyindexer.Length; i++)
            {
                Console.WriteLine("Indexer : {0}, Value :{1} ", i, changebyindexer[i]);
            }
            Console.WriteLine();
        }
    }

Result:
Original Builder:

Indexer: 0, Value: A

Indexer: 1, Value: B

Indexer: 2, Value: C

Indexer: 3, Value: D

Builder after modification:

Indexer: 0, Value: A

Indexer: 1, Value: 1

Indexer: 2, Value: C

Indexer: 3, Value: 2

Press any key to continue . . .

No comments:

Post a Comment

My Presentations