Summary - Advanced strings
Combine Substring, Split and Replace to write a CSV parser.
Summary - Advanced string methods
In this group you learned five commonly used string tools. Substring takes a slice; IndexOf and LastIndexOf give a substring's position; Split and string.Join break apart and merge; Trim and Pad clean and align edges; Replace swaps substrings.
None of them mutate the original; they all return a new string. That is why you should always assign the result to a variable. Most throw if you cross the string's bounds, so checking the -1 return from IndexOf is a good habit.
Combining in practice
In real projects you often use these methods together. You might pull the domain out of an email with IndexOf + Substring, turn a comma-separated list into an array with Split, then clean each item with Trim. Using PadLeft to align output is common.
Recognising these patterns speeds up real text-processing tasks. In the next exercise you will try them all together.
Exercise Clean and align a name list
Split the comma-separated names in raw into an array called names. Use a foreach loop to trim each name with Trim, pad it with PadRight(8) and print it with Console.WriteLine.
Show example solution
Split with names = raw.Split(','); then foreach (string n in names) { Console.WriteLine(n.Trim().PadRight(8)); }
Example solution:
using System;
class Program
{
static void Main()
{
string raw = "alex , mary , john";
string[] names = raw.Split(',');
foreach (string n in names)
{
Console.WriteLine(n.Trim().PadRight(8));
}
}
}
Test yourself
-
Match each method to its job
- Substring
- Take a slice
- IndexOf
- Find first position
- Split
- Break at separator
- Replace
- Swap a substring
-
Which method breaks a string into pieces?
string[] parts = "a,b,c".Split(',');- Substring
- Replace
- Split
- Trim
Show answer
Substring — Correct! Split breaks a string around a separator.