Ebooks

C# StringBuilder

C# StringBuilder tutorial shows how to use StringBuilder in C#. String objects are immutable; it is only possible to create mofied copies of the original string. When we need to modify strings in-place, we use StringBuilder.

StringBuilder

StringBuilder is a mutable sequence of characters. StringBuilder is used when we want to modify C# strings in-place.

StringBuilder has methods such as Append(), Insert(), or Replace() that allow to modify strings.

C# StringBuilder is mutable

C# String is immutable while StringBuilder is mutable.

Program.cs
using System;
using System.Text;

namespace MutableImmutable
{
    class Program
    {
        static void Main(string[] args)
        {
            var word = "rock";
            var word2 = word.Replace('r', 'd');

            Console.WriteLine(word2);

            var builder = new StringBuilder("rock");
            builder.Replace('r', 'd');

            Console.WriteLine(builder);
        }
    }
}

The example demonstrates the main difference between String and StringBuilder.

var word2 = word.Replace('r', 'd');

C# String has a Replace() method but it does not modify the original string. It creates a modified copy instead.

var builder = new StringBuilder("rock");
builder.Replace('r', 'd');

On the other hand, the StringBuilder replaces the string in-place.

Console.WriteLine(builder);

The Console.WriteLine method invokes the StringBuilder's ToString() method, which converts the value of the builder to a string.

$ dotnet run
dock
dock

This is the output.

C# StringBuilder Append and AppendLine

The Append method appends the string representation of a specified object to the builder. The AppendLine method appends the default line terminator to the end of the current StringBuilder object.

Program.cs
using System;
using System.Text;

namespace Appending
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder= new StringBuilder("There are");

            builder.Append("three hawks ");
            builder.Append("in the sky");

            builder.AppendLine();

            builder.AppendLine("The weather is beautiful");
            builder.Append("The flowers blossom");

            Console.WriteLine(builder);
        }
    }
}

The example builds a string using Append() and AppendLine() methods.

var builder= new StringBuilder("There are");

builder.Append("three hawks ");
builder.Append("in the sky");

builder.AppendLine();

Here we add one sentence to the StringBuilder.

builder.AppendLine("The weather is beautiful");

We can add a sentence and a new line in one go.

$ dotnet run
There arethree hawks in the sky
The weather is beautiful
The flowers blossom

This is the output.

C# StringBuilder AppendFormat

The AppendFormat method allows to add a formatted string to the StringBuilder.

Program.cs
using System;
using System.Text;

namespace AppendFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "Peter";
            int age = 34;

            var builder = new StringBuilder();

            builder.AppendFormat("{0} is {1} years old", name, age);

            Console.WriteLine(builder);
        }
    }
}

In the example, we build a string with AppendFormat.

$ dotnet run
Peter is 34 years old

This is the output.

C# StringBuilder Insert

The Insert method is used to insert a string into the specified position of the builder.

Program.cs
using System;
using System.Text;

namespace Inserting
{
    class Program
    {
        static void Main(string[] args)
        {
            var sentence = "There is a red fox in the forest.";
            var builder = new StringBuilder(sentence);

            builder.Insert(19, "and a wolf ");

            Console.WriteLine(builder);
        }
    }
}

The example inserts a string into a sentence with the Insert method.

$ dotnet run
There is a red fox and a wolf in the forest.

We have created this sentence.

C# StringBuilder Replace

The Replace method replaces a substring in the string builder with the specified new string.

Program.cs
using System;
using System.Text;

namespace Replacing
{
    class Program
    {
        static void Main(string[] args)
        {
            var sentence = "I saw a red fox running into the forest.";
            var builder = new StringBuilder(sentence);

            var term = "fox";
            var newterm = "dog";

            int idx = builder.ToString().IndexOf(term);
            int len = term.Length;

            builder.Replace(term, newterm, idx, idx + len);

            Console.WriteLine(builder);
        }
    }
}

The example replaces the word fox with dog.

int idx = builder.ToString().IndexOf(term);

We find the beginning index of the substring to be replaced.

int len = term.Length;

We get the length of the substring.

builder.Replace(term, newterm, idx, idx + len);

We call the Replace method. The first parameter is the old value, the second parameter the new value. The next two parameters are the starting index and the length of the substring.

$ dotnet run
I saw a red dog running into the forest.

This is the output.

C# StringBuilder Remove

The Remove method removes the specified range of characters from this instance.

Program.cs
using System;
using System.Text;

namespace Removing
{
    class Program
    {
        static void Main(string[] args)
        {
            var sentence = "There is a red fox in the forest.";
            var builder = new StringBuilder(sentence);

            builder.Remove(11, 3);
            Console.WriteLine(builder);

            builder.Remove(11, 1);
            Console.WriteLine(builder);
        }
    }
}

The example deletes a few characters from a string.

builder.Remove(11, 3);

With the Remove method, we delete a substring.

builder.Remove(11, 1);

We delete another character.

$ dotnet run
There is a  fox in the forest.
There is a fox in the forest.

This is the output.

In this tutorial, we have worked with C# StringBuilder.

Read C# tutorial or list all C# tutorials.