Manipulating Strings in C#—Joining a String

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

Manipulating Strings in C#

© 2003 Peachpit Press

Joining a String

Joining a string is the opposite of splitting a string. It's done by invoking the Join function in System.String and passing an array of strings containing all the pieces you wish to join, and a string with the characters to use as a delimiter. The Join function then returns a single string by gluing all the segments from the array together and placing the delimiter between them.

To create a string by joining other strings:

1. Type string[] pieces = new string[10]; where pieces is a variable to store a set (array) of strings, and 10 is the number of segments that you wish to glue together.
2. Type pieces[0] = "any string"; where pieces is the variable declared in step 1 and [0] is the element in the array that you wish to set. You can set each element in the string array by specifying the index from zero to the number of elements minus one.
3. Declare a string variable to hold the new string resulting from the join.
4. Type =System.String.Join(",",pieces); where "," is the character to use as a delimiter and pieces is the array of strings (Figure 4.53).


Image:CSharpWebDevASPNET4-53.gif
Figure 4.53. Join does the opposite of Split—it creates one string from an array of strings and uses a delimiter to join each piece.


Tip

  • The delimiter string doesn't have to be a single character. It can be a series of characters, as in Figure 4.54.


Image:CSharpWebDevASPNET4-54.gif
Figure 4.54. When you put strings together with Join you aren't limited to a single character to put in between each segment.


Previous_Page_.gif Next_Page_.gif


Personal tools