[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Split and join strings in C#

[Split and join strings in C#]

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[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); // Rejoin them. string result = String.Join(";", values); // Display the result. txtResult.Text = result; }

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.