Team LiB
Previous Section Next Section

String Concatenation

String concatenation is used to add characters to the end of a string. The string class provides two methods for adding characters to a string:

The StringBuilder class is convenient for string concatenation, as well as other types of string modifications, such as removing, replacing, or inserting characters. Unlike the string class, which creates an entire new object for each change to the string, with the StringBuilder class, you can avoid creating a new string subsequent to each modification. The methods contained within this class do not return a new StringBuilder object, unless you specify otherwise. This makes the StringBuilder class a much better solution for operating on strings.

The following examples demonstrate string concatenation with mutable and nonmutable strings, as well as comparing strings.

Code Example: String Concatenation
Start example
using System;
using System.Text;

namespace Client.Chapter_6___Strings
{
      class StringConcatenation
      {
            static void Main(string[] args)
            {
                 //Creates a mutable string
                  StringBuilder MyString = new
                  StringBuilder("Hello");

                  MyString.Insert(0, "My");
                  MyString.Append("World");

                  Console.WriteLine(MyString);
            }
      }
}
End example
Code Example: Nonmutable String
Start example

using System;

namespace Client.Chapter_6___Strings
{
      class StringConcatenation2
      {
            static void Main(string[] args)
            {
                  Console.WriteLine("Enter Your Password?");
                  string UserPassword = Console.ReadLine();
                 //Creates a nonmutable string
                  string Password = "Victory";
                 //Compares the value of the string
                  if(Password.CompareTo(UserPassword) == 0)
                  {
                        Console.WriteLine("Bad Password");
                  }

                 Console.WriteLine("Good Password!");
            }
      }
}
End example

Team LiB
Previous Section Next Section