BLOG.CSHARPHELPER.COM: Use Split and Join to split delimited text into values and join it back together again in C#
Use Split and Join to split delimited text into values and join it back together again in C#
The String class's Split method splits a string into pieces separated by delimiters. Different overloaded versions lets 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 takes a variable parameter list so you can pass in any number of char parameters. 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 joins the values in an array of strings with a separator string.
The following code shows how the example splits the text you enter at spaces removing duplicates, and then rejoins the values separated 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[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// Rejoin them. string result = String.Join(";", values);
Comments