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 ).

    Figure 4.53 Join does the opposite of Splitit creates one string from an array of strings and uses a delimiter to join each piece.
     string[] characters = new string[5]; characters[0] = "Mickey"; characters[1] = "Minnie"; characters[2] = "Pluto"; characters[3] = "Goofy"; characters[4] = "Donald"; string Disney =  string.Join(",",characters);  Response.Write(Disney); /* outputs: Mickey,Minnie,Pluto,Goofy,Donald */ 

graphics/tick.gif Tip

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

    Figure 4.54 When you put strings together with Join you aren't limited to a single character to put in between each segment.
     string[] phrases = new string[5]; phrases[0] = "Hi"; phrases[1] = "How are you"; phrases[2] = ""; phrases[3] = "Like we got to get together"; phrases[4] = "ok"; string collegeTalk = string.Join(  " dude "  ,phrases); Console.WriteLine(collegeTalk); /* outputs: Hi dude How are you dude dude Like we got to get together dude ok */ 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net