Team LiB
Previous Section Next Section

Joining and Splitting Strings

The easiest way to join two strings together is to use the overloaded + operator to form a new string. Another approach is to use the Join method of the string class, which combines two strings with a separator that you define.

The Split method of the string class allows you to break an existing string into an array of strings by searching for a particular character, such as a space.

The following examples demonstrate how to join and split strings. In the first example, the two strings are joined together by using the + operator to form a new string, which is passed to WriteLine.

Code Example: Joining Strings
Start example
Using System;

namespace Client.Chapter_6___Strings
{
      class JoiningStrings
      {
            static void Main(string[] args)
            {
                  string MyString = "Hello";
                  string MyString2 = "World";
                  string JoinedString = MyString + MyString2;

                  Console.WriteLine(JoinedString);

                  string[] A = new string[2] {
                        "Hello", "World"
                  };
                 //Combines all the strings in the string array with a space
                 //in between each string
                  string Joined = string.Join(" ", A);

                  Console.WriteLine(Joined);
            }
      }
}
End example
Code Example: Splitting Strings
Start example

using System;

namespace Client.Chapter_6___Strings
{
      class SplittingStrings
      {
            static void Main(string[] args)
            {
                  string MyString = "The quick brown fox ran around!";
                  string[] MyStringSplit = new string[6];

                  MyStringSplit = MyString.Split(new char[] { ' ' }, 6);
                  Console.WriteLine(MyStringSplit[1] + MyStringSplit[3]);
            }
      }
}
End example

Team LiB
Previous Section Next Section