Sunday, September 11, 2011

C#/.NET Little Wonders: The String Split() and Join() methods

This post continues a series of Little Wonders in the BCL String class.  Yes, we all work with strings in .NET daily, so perhaps you already know most of these.  However, there are a lot of little fun things that the String class can do that often get overlooked.

Today we are going to look at a pair of String method families to Split() and Join() string data.
Background

Many times when dealing with string data – especially data coming to or from files – we may need to divide a string based on a set of delimiters (like commas in CSV files) or join a sequence of strings together using a delimiter.

Many people know about the Split() method for busting apart strings, but fewer tend to know of its counterpart, the Join() method for putting a sequence of strings together.  So let’s look at both.
Split() – split string into parts based on delimiters

Many people know about the Split() method, but it actually has some interesting options we’ll discuss for a bit before heading to Join().

The Split() method is useful for taking a string that is logically divided by delimiters and busting it into an array of the strings between the delimiters.  The resulting array will have one entry for every string separated by the delimiters, and all the delimiters will be removed.

The delimiters to split can logically be one of several forms:

    An array of 1 character:
        For example ‘,’ or new [] { ‘,’ } as in: “A,B,C,D,E,F”
    An array of many characters:
        For example, ‘,’, ‘-‘, ‘*’ or new [] { ‘,’ ‘-‘ ‘*’ } as in: “A,B-C,D*E,F”
    An array of one string:
        For example, new [] { “=>” } as in: “A=>B=>C=>D=>E=>F”
    An array of many strings:
        For example, new [] { “=>”, “<=” } as in: “A=>B<=C=>D<=E=>F”


Read more: James Michael Hare
QR: c.net-little-wonders-the-string-split-and-join-methods.aspx

Posted via email from Jasper-Net