Sponsored Ad

Wednesday, November 4, 2009

Joining and Splitting Strings in C#

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:

Code Snippet
  1. using System;
  2.  
  3. namespace csharp_station.howto
  4. {
  5. class StringJoinSplit
  6. {
  7. static void Main(string[] args)
  8. {
  9. // comma delimited string
  10. string commaDelimited = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
  11.  
  12. Console.WriteLine("Original Comma Delimited String: \n{0}\n", commaDelimited);
  13.  
  14. // separate individual items between commas
  15. string[] year = commaDelimited.Split(new char[] {','});
  16.  
  17. Console.WriteLine("Each individual item: ");
  18.  
  19. foreach(string month in year)
  20. {
  21. Console.Write("{0} ", month);
  22. }
  23. Console.WriteLine("\n");
  24.  
  25. // combine array elements with a new separator
  26. string colonDelimeted = String.Join(":", year);
  27.  
  28. Console.WriteLine("New Colon Delimited String: \n{0}\n", colonDelimeted);
  29.  
  30. string[] quarter = commaDelimited.Split(new Char[] {','}, 3);
  31.  
  32. Console.WriteLine("The First Three Items: ");
  33.  
  34. foreach(string month in quarter)
  35. {
  36. Console.Write("{0} ", month);
  37. }
  38. Console.WriteLine("\n");
  39.  
  40. string thirdQuarter = String.Join("/", year, 6, 3);
  41.  
  42. Console.WriteLine("The Third Quarter: \n{0}\n", thirdQuarter);
  43. }
  44. }
  45. }

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

Sponsored Ad

Website Update

Followers