Recipe2.17.Creating a Delimited String


Recipe 2.17. Creating a Delimited String

Problem

You have an array of strings to format as delimited text and possibly to store in a text file.

Solution

Using the static Join method of the String class, the array of strings can be easily joined in as little as one line of code. For example:

 string[] infoArray = new string[5] {"11", "12", "Checking", "111", "Savings"}; string delimitedInfo = string.Join(",", infoArray); 

This code sets the value of delimitedInfo to the following:

 11,12,Checking,111,Savings 

Discussion

The Join method concatenates all the strings contained in a string array. Additionally, a specified delimiting character(s) is inserted between each string in the array. This method returns a single string object with the fully joined and delimited text.

Unlike the Split method of the String class, the Join method accepts only one delimiting character at a time. In order to use multiple delimiting characters within a string of values, subsequent Join operations must be performed on the information until all of the data has been joined together into a single string. For example:

 string[] infoArray = new string[4] {"11", "12", "Checking", "Savings"}; string delimitedInfoBegin = string.Join(",", infoArray, 0, 2); string delimitedInfoEnd = string.Join(",", infoArray, 2, 2); string[] delimitedInfoTotal = new string[2] {delimitedInfoBegin,          delimitedInfoEnd}; string delimitedInfoFinal = string.Join(":", delimitedInfoTotal); Console.WriteLine(delimitedInfoFinal); 

produces the following delimited string:

 11,12:Checking,Savings 

See Also

See the "String.Join Method" topic in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

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