.Net Programming - Financial independence

String Concatenation and the StringBuilder in Visual Basic/C#

In this tutorial we’re going to explore the String concatenation. It’s a very important part of any programming language and Visual Basic and C# are no exception. You’ll see that there are multiple ways of merging Strings together and you can use the one you prefer or even use multiple at the same time depending on the situation!

String concatenation

We’ve been using it for quite some time but I would like to make things clear on the subject. There are four major ways of doing String concatenation (put Strings together).

You can:
Use “+”, “&” operator;
Use the String Builder;
Use String.Format;
Use the $””.

Let’s look at some examples.

+ and & operators

Here is what it looks like with the “&” (in Visual Basic) and “+” (in C#) operators, notice how the &= and += are equivalent to doing:

Visual Basic: variable = variable & “Hello”
C#: variable = variable + “Hello”;

You can stack up as many as you want by adding &/+ an another string value, just like that.

Visual Basic: variable = variable & “Hello” & ” how are you?”
C#: variable = variable + “Hello” + ” how are you?”;

You can even put variables inside like variableTwo which would have been declared previously.

Visual Basic: variable = variable & “Hello” & ” how are you?” & variableTwo
C#: variable = variable + “Hello” + ” how are you?” + variableTwo;

Visual Basic

Option Strict On
Option Explicit On

Module Program

    Sub Main()
        ' "&" operator
        ' We create an initial string start.
        Dim finalString As String = "Start"

        ' We add 1001 occurences of "Step"
        For Index As Integer = 0 To 1000 Step 1
            finalString &= "Step"
        Next

        ' We then add "Finish" to the string and display it in the console.
        finalString &= "Finish"

        Console.WriteLine(finalString)

        ' This will stop the execution of the console.
        Console.ReadKey()
    End Sub

End Module

C#

using System;

namespace StringConcatenationCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // "&" operator
            // We create an initial string start.
            string finalString = "Start";

            // We add 1001 occurences of "Step"
            for (int index = 0; index <= 1000; index++)
                finalString += "Step";

            // We then add "Finish" to the string and display it in the console.
            finalString += "Finish";

            Console.WriteLine(finalString);

            // This will stop the execution of the console.
            Console.ReadKey();
        }
    }
}

Note: don’t forget to change the namespace to your project’s name. Also this is in a console application.

The StringBuilder Class

The StringBuilder is a class but you can think of it as a String value in memory to which you can do operations. In our case we will only use the Append() method to add some more content to our String but there are multiple others to do more. Here is what the same as the above example would look like using the StringBuilder:

Visual Basic

Option Strict On
Option Explicit On
Imports System.Text

Module Program

    Sub Main()
        ' StringBuilder
        ' Declare and initialize the StringBuider!
        Dim activeStringBuilder As StringBuilder = New StringBuilder

        ' We create an initial string start.
        activeStringBuilder.Append("Start")

        ' We add 1000 occurences of "Step".
        For Index As Integer = 0 To 1000 Step 1
            activeStringBuilder.Append("Step")
        Next

        ' We then add "finish" to the string and display it in the console.
        activeStringBuilder.Append("Finish")

        ' The ToString() method of the StringBuilder will give us all the content.
        Console.WriteLine(activeStringBuilder.ToString())
        Console.ReadKey()
    End Sub

End Module

C#

using System;
using System.Text;

namespace StringConcatenationCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // StringBuilder
            // We create an initial string start.
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("Start");

            // We add 1001 occurences of "Step"
            for (int index = 0; index <= 1000; index++)
                stringBuilder.Append("Step");

            // We then add "finish" to the string and display it in the console.
            stringBuilder.Append("Finish");

            // The ToString() method of the StringBuilder will give us all the content.
            Console.WriteLine(stringBuilder.ToString());

            // This will stop the execution of the console.
            Console.ReadKey();
        }
    }
}

Notice how the StringBuilder uses the ToString() method to output everything it stored every time you called the Append() method. You can actually call the ToString() anytime you want, but you have to call Clear() to clean the content of your StringBuilder.

String.Format

String.Format() will take a String in parameter and you will have to add “{0}”, “{1}” and so on matching the parameters that follow. It’s like an array, it’s going to replace {0} by the first parameter you will supply, {1} by the second and so on. The following example will illustrate better what I’m talking about.

Visual Basic

Option Strict On
Option Explicit On
Imports System.Text

Module Program

    Sub Main()
        ' String.Format()
        ' I declare and initialize two variables.
        Dim name As String = "Alexandre"
        Dim age As Integer = 29

        ' Then I create the string using String.Format, notice how {0} will be replaced by the value of name
        ' and {1} will be replaced by the value of age.
        Dim formattedString As String = String.Format("Hello, my name is {0}, and I'm {1} years old!", name, age)

        Console.WriteLine(formattedString)
        Console.ReadKey()
    End Sub

End Module

C#

using System;
using System.Text;

namespace StringConcatenationCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // I declare and initialize two variables.
            string name = "Alexandre";
            int age = 29;

            // Then I create the string using String.Format, notice how {0} will be replaced by the value of name
            // and {1} will be replaced by the value of age.
            string formattedString = String.Format("Hello, my name is {0}, and I'm {1} years old!", name, age);

            Console.WriteLine(formattedString);
            Console.ReadKey();
        }
    }
}

$””

This one is newer, it enables us to put variables straight in the String! You’ll see in the following example how convenient it is. Just make sure you don’t forget the $ in front of the string.

Visual Basic

Option Strict On
Option Explicit On
Imports System.Text

Module Program

    Sub Main()
        ' $""
        ' I declare two numbers to use in the String.
        Dim firstNumber As Integer = 9
        Dim secondNumber As Integer = 5

        ' Notice how you can even do operations in the middle of the String, no problem! It's just like String.Format but
        ' with the values directly in the String instead of {0} And {1} And so on.
        Dim formattedStringWithDollarSign As String = $"The sum of {firstNumber} and {secondNumber} is {firstNumber + secondNumber}!"

        Console.WriteLine(formattedStringWithDollarSign)
        Console.ReadKey()
    End Sub

End Module

C#

using System;
using System.Text;

namespace StringConcatenationCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal firstNumber = 9;
            decimal secondNumber = 5;

            // Notice how you can even do operations in the middle of the String, no problem! It's just like String.Format but
            // with the values directly in the String instead of {0} and {1} and so on.
            string formattedStringWithDollarSign = $"The sum of {firstNumber} and {secondNumber} is {firstNumber + secondNumber}!";

            Console.WriteLine(formattedStringWithDollarSign);
            Console.ReadKey();
        }
    }
}

This one is my personal favourite for any concatenation except in loops, then I’ll use the StringBuilder because it’s very quick! How convenient is that to be able to put variable names directly in the String, it’s just like String.Format but easier to see. I strongly suggest using this version.

To Summarize

If you wish to concatenate String, you can use the “&” (Visual Basic) or “+” (C#) operator, but the StringBuilder class is the best choice for loop concatenation or other concatenation operation that might be CPU intensive. The String.Format and $”” are better if you want your code to look prettier, I would recommend them over the “&” and the “+”.

You can find more information on the MSDN Website if you wish to look it up!

Here is the complete code in both languages

Visual Basic

Option Strict On
Option Explicit On
Imports System.Text

Module Program

    Sub Main()
        ' "&" operator
        ' We create an initial string start.
        Dim finalString As String = "Start"

        ' We add 1000 occurences of "Step"
        For Index As Integer = 0 To 1000 Step 1
            finalString &= "Step"
        Next

        ' We then add "finish" to the string and display it in the console.
        finalString &= "Finish"

        Console.WriteLine(finalString)

        ' This will stop the execution of the console.
        Console.ReadKey()

        ' StringBuilder
        ' Declare and initialize the StringBuider!
        Dim activeStringBuilder As StringBuilder = New StringBuilder

        ' We create an initial string start.
        activeStringBuilder.Append("Start")

        ' We add 1000 occurences of "Step".
        For Index As Integer = 0 To 1000 Step 1
            activeStringBuilder.Append("Step")
        Next

        ' We then add "finish" to the string and display it in the console.
        activeStringBuilder.Append("finish")

        ' The ToString() method of the StringBuilder will give us all the content.
        Console.WriteLine(activeStringBuilder.ToString())
        Console.ReadKey()

        ' String.Format()
        ' I declare and initialize two variables.
        Dim name As String = "Alexandre"
        Dim age As Integer = 29

        ' Then I create the string using String.Format, notice how {0} will be replaced by the value of name
        ' and {1} will be replaced by the value of age.
        Dim formattedString As String = String.Format("Hello, my name is {0}, and I'm {1} years old!", name, age)

        Console.WriteLine(formattedString)
        Console.ReadKey()

        ' $""
        ' I declare two numbers to use in the String.
        Dim firstNumber As Integer = 9
        Dim secondNumber As Integer = 5

        ' Notice how you can even do operations in the middle of the String, no problem! It's just like String.Format but
        ' with the values directly in the String instead of {0} And {1} And so on.
        Dim formattedStringWithDollarSign As String = $"The sum of {firstNumber} and {secondNumber} is {firstNumber + secondNumber}!"

        Console.WriteLine(formattedStringWithDollarSign)
        Console.ReadKey()
    End Sub

End Module

C#

using System;
using System.Text;

namespace StringConcatenationCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // "+" Concatenation
            // We create an initial string start.
            string finalString = "Start";

            // We add 1001 occurences of "Step"
            for (int index = 0; index <= 1000; index++)
                finalString += "Step";

            // We then add "finish" to the string and display it in the console.
            finalString += "finish";

            Console.WriteLine(finalString);

            // This will stop the execution of the console.
            Console.ReadKey();

            // StringBuilder
            // We create an initial string start.
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("Start");

            // We add 1001 occurences of "Step"
            for (int index = 0; index <= 1000; index++)
                stringBuilder.Append("Step");

            // We then add "finish" to the string and display it in the console.
            stringBuilder.Append("Finish");

            // The ToString() method of the StringBuilder will give us all the content.
            Console.WriteLine(stringBuilder.ToString());

            // This will stop the execution of the console.
            Console.ReadKey();

            // String.Format
            // I declare and initialize two variables.
            string name = "Alexandre";
            int age = 29;

            // Then I create the string using String.Format, notice how {0} will be replaced by the value of name
            // and {1} will be replaced by the value of age.
            string formattedString = String.Format("Hello, my name is {0}, and I'm {1} years old!", name, age);

            Console.WriteLine(formattedString);
            Console.ReadKey();

            // $""
            decimal firstNumber = 9;
            decimal secondNumber = 5;

            // Notice how you can even do operations in the middle of the String, no problem! It's just like String.Format but
            // with the values directly in the String instead of {0} and {1} and so on.
            string formattedStringWithDollarSign = $"The sum of {firstNumber} and {secondNumber} is {firstNumber + secondNumber}!";

            Console.WriteLine(formattedStringWithDollarSign);
            Console.ReadKey();
        }
    }
}

Found an error in the code? Please send me a message so I can fix it as soon as possible!

YouTube

Next article How to Use 1D and 2D Arrays in Visual Basic
Previous article Loops in Visual Basic - Exercise and Solution

Related posts

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Comment

Your data will be safe! Your e-mail address will not be published. Also other data will not be shared with third person. Required fields marked as *