When developing programs that interoperate with external systems, it is often necessary to process data in a common format. For example, a program could process data from an Excel spreadsheet. Excel has the ability to export a spreadsheet in Comma Separated Values (CSV). Using the string method split () to extract values between the commas. Similarly, the string join () method will be individual values in an array and combine them with a separator like a comma. The following list shows how to use the chain of Split () and Join () methods:
- using System;
- namespace csharp_station.howto
- {
- class StringJoinSplit
- {
- static void Main(string[] args)
- {
- // comma delimited string
- string commaDelimited = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
- Console.WriteLine("Original Comma Delimited String: \n{0}\n", commaDelimited);
- // separate individual items between commas
- string[] year = commaDelimited.Split(new char[] {','});
- Console.WriteLine("Each individual item: ");
- foreach(string month in year)
- {
- Console.Write("{0} ", month);
- }
- Console.WriteLine("\n");
- // combine array elements with a new separator
- string colonDelimeted = String.Join(":", year);
- Console.WriteLine("New Colon Delimited String: \n{0}\n", colonDelimeted);
- string[] quarter = commaDelimited.Split(new Char[] {','}, 3);
- Console.WriteLine("The First Three Items: ");
- foreach(string month in quarter)
- {
- Console.Write("{0} ", month);
- }
- Console.WriteLine("\n");
- string thirdQuarter = String.Join("/", year, 6, 3);
- Console.WriteLine("The Third Quarter: \n{0}\n", thirdQuarter);
- }
- }
- }
output:
Original Comma Delimited String:
Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
Each individual item:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
New Colon Delimited String:
Jan:Feb:Mar:Apr:May:Jun:Jul:Aug:Sep:Oct:Nov:Dec
The First Three Items:
Jan Feb Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
The Third Quarter:
Jul/Aug/Sep
0 comments:
Post a Comment