Split and join strings in C#

[Split and join strings]

This example shows how you can use string methods to split and join strings.

The string class’s Split method splits a string into pieces separated by delimiters. Different overloaded versions let you pass in an array of delimiters to use, a count indicating the maximum number of values that should be returned, and options that let you decide whether Split should remove duplicates. Removing duplicates is particularly useful if you’re splitting a string delimited by spaces and the string includes multiple spaces in a row.

One overloaded version of the Split method takes a variable parameter list so you can pass in any number of char parameters to use as delimiters. If you pass no parameters (0 is an allowed number), the method defaults to breaking the string at white space characters such as space, tab, and line feed.

The String class’s Join method concatenates the values in an array of strings, separating the strings with separator string.

The following code shows how the example splits the text you enter at spaces removing duplicates, and then rejoins the values separating them with semi-colons.

// Split the values and then recombine them with Join.
private void btnSplit_Click(object sender, EventArgs e)
    // Get the string of values.
    string txt = txtValues.Text;

    // Split the values at spaces, removing duplicates.
    string[] values = txt.Split(new char[] { ' ' },

    // Rejoin them.
    string result = String.Join(";", values);

    // Display the result.
    txtResult.Text = result;

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in parsing, strings, variables and tagged , , , , , , , , , , , . Bookmark the permalink.