Learn C# · lesson 35 of 61 · about 8 minutes
Split and Join
Read a combo typed on one line: break text into pieces with Split, clean them up, and put them back together with string.Join.
What you'll learn
- Split on a character or several
- Remove empty entries and trim
- Join pieces with a separator
A combo
Before the next fight, the hero plans a combo, typed on one line with commas between the moves, like slash, fire,,Slash. The line is made lower case and cut at the commas with Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries), so the spaces around each move go, and the empty piece between the two commas is dropped. Moves the hero knows are looked up in a dictionary of damage and joined back together with string.Join(" > ", known); any others are listed as unknown.
Taking text apart
"a,b,c".Split(',')gives["a", "b", "c"]Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries)splits on several characters and drops empty pieces- Add
| StringSplitOptions.TrimEntriesto trim each piece too string.Join(" - ", parts)puts them back with a separator
Cleaning a list
string raw = " milk, eggs,,bread , ";
string[] items = raw.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
Console.WriteLine($"{items.Length} items: {string.Join(" | ", items)}");
string csv = "Ada,12,London";
string[] f = csv.Split(',');
Console.WriteLine($"{f[0]} is {f[1]} and lives in {f[2]}");
Console.WriteLine(string.Join("", "hello".Reverse()));Output
3 items: milk | eggs | bread
Ada is 12 and lives in London
ollehSplitting on a string
Split can also cut on a whole string, like Split(" > "), but only where all of it appears. That's fine for text a program wrote, where the spacing is always the same. For text people type, splitting on the single character and trimming each piece is safer.
A path through the dungeon
string path = "Bat > Goblin > Troll";
string[] steps = path.Split(" > ");
Console.WriteLine($"{steps.Length} {steps[^1]}");Output
3 TrollNow try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.