Split and Join
Learn to split with Split and join with Join.
Splitting with Split
The Split method breaks a string into pieces around a separator character and returns the pieces as a string array. It is ideal for comma-separated values, space-separated words or period-separated sentences.
For example, "alex,mary,john".Split(',') returns an array of three elements. The separator itself is not kept. Since the return type is string[], you can iterate it with foreach.
Joining with string.Join
The string.Join method merges a string array (or list) into a single string with a separator between elements. It is the inverse of Split: it takes pieces and inserts a separator. The first argument is the separator, the second is the collection.
Example: string.Join("-", new[] { "a", "b", "c" }) returns "a-b-c". It is commonly used to build file paths, date formats or CSV lines.
Removing empty entries
By default, Split keeps empty strings between consecutive separators. To avoid that, pass StringSplitOptions.RemoveEmptyEntries so empty pieces are dropped from the result.
Example: "a,,b".Split(',', StringSplitOptions.RemoveEmptyEntries) returns only two elements. When users type extra spaces or separators, this option gives you a clean array.
Exercise Split the names and join with a dash
Use Split to break the comma-separated names into an array called parts. Then use string.Join to merge that array with a dash ("-") into result and print it with Console.WriteLine.
Show example solution
First split with parts = names.Split(','); then join with result = string.Join("-", parts); and print.
Example solution:
using System;
class Program
{
static void Main()
{
string names = "alex,mary,john";
string[] parts = names.Split(',');
string result = string.Join("-", parts);
Console.WriteLine(result);
}
}
Test yourself
-
What does Split return?
string[] parts = "a-b-c".Split('-');- a single string
- string[]
- List<string>
- char[]
Show answer
char[] — Correct! Split takes a char[] parameter but returns string[].
-
Join the array with a dash
string[] parts = { "a", "b", "c" }; string joined = string____; Console.WriteLine(joined);Show answer
string[] parts = { "a", "b", "c" }; string joined = string.Join("-", parts); Console.WriteLine(joined); -
Match the call with its result
- "a,b,c".Split(',')
- 3 elements
- "a-b-c".Split('-').Length
- 3
- string.Join(",", new[] {"x","y"})
- "x,y"