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 Insert method allows you to specify where to place the new characters in the string. It has two parameters: the location where you would like to add to the string, followed by the string to be added to the existing string.
The Append method allows you to add a string to the end of an existing string. The only parameter you pass to this method is the string to be added.
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.
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);
}
}
}
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!"); } } }