Working with strings and interpolation
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
Text is everywhere
Most programs spend a lot of time with text: names, messages, file paths, reports. A C# string is a sequence of characters. It comes with many methods for the jobs you do all the time. In this lesson you learn the ones I reach for every week.
Joining text
You can join strings with +. It works but becomes hard to read quickly. String interpolation is cleaner. Put a $ before the opening quote, and write any expression inside curly braces.
string first = "Ayesha";
string last = "Khan";
int items = 3;
decimal price = 249.5m;
// Interpolation
Console.WriteLine($"Hello, {first} {last}!");
Console.WriteLine($"{items} items cost {items * price:F2} rupees");
// Formatting inside the braces
Console.WriteLine($"Price: {price,10:N2}|");
Console.WriteLine($"Today: {DateTime.Now:yyyy-MM-dd}");
// Useful methods
string email = " Ayesha.Khan@Example.com ";
string clean = email.Trim().ToLower();
Console.WriteLine(clean);
Console.WriteLine(clean.Length);
Console.WriteLine(clean.Contains("example"));
Console.WriteLine(clean.StartsWith("ayesha"));
Console.WriteLine(clean.Replace("example", "mail"));
Console.WriteLine(clean.IndexOf('@'));
string user = clean.Substring(0, clean.IndexOf('@'));
Console.WriteLine(user);
string[] parts = "red,green,blue".Split(',');
Console.WriteLine(parts.Length);
Console.WriteLine(string.Join(" | ", parts));
Walking through it
Inside the braces, anything after a colon is a format string. F2 means fixed-point with two decimals. N2 adds thousands separators and two decimals. yyyy-MM-dd is a date pattern. The comma and number in {price,10:N2} set a minimum width of 10 characters, which is useful for aligned columns.
Trim removes spaces from both ends, and ToLower makes everything lowercase. Notice that I chained them: email.Trim().ToLower(). Each method returns a new string and the next method works on that result.
Substring(start, length) cuts out part of the text. Positions start at zero. IndexOf returns the position of a character, or -1 if it is not found. Checking for -1 before you call Substring will save you from an exception.
Split turns one string into an array, and string.Join does the opposite.
Strings never change
A string is immutable. Methods like ToLower and Replace do not change the original. They return a new one. This catches nearly every beginner at least once:
string name = " murtaza ";
name.Trim(); // result thrown away, name is unchanged
name = name.Trim(); // correct
When you build a very large string in a loop, adding to it thousands of times creates thousands of temporary strings. For that, use StringBuilder. For small jobs, ordinary joining is fine.
Special characters
A backslash starts an escape sequence inside a normal string. \n is a new line, \t is a tab, \" is a quote mark, and \\ is one backslash. Windows file paths are where this hurts, because "C:\new\table" contains a new line and a tab. Put an @ before the quote for a verbatim string, where backslashes are literal:
string path = @"C:\Users\Murtaza\notes.txt";
string json = """
{ "name": "Ayesha", "age": 29 }
""";
The second example is a raw string literal, written with three double quotes. It lets you include quotes and line breaks without any escaping. It is excellent for JSON and SQL.
Comparing strings
Use == to compare strings for equality. It compares content, not identity, so it does what you expect. It is case-sensitive. For a case-insensitive check, use string.Equals(a, b, StringComparison.OrdinalIgnoreCase). Never lowercase both strings just to compare. It allocates new strings for no reason.
Common mistakes
- Ignoring the return value of
Trim,Replaceand friends. - Forgetting the
$and seeing{name}printed literally. - Calling
Substringwith a bad index. It throwsArgumentOutOfRangeException. - Using
+in a big loop. UseStringBuilderorstring.Join.
Try it yourself
- Store the text
" Learn C# Step By Step "in a variable. Print it trimmed, in uppercase, and with its length before and after trimming. - Given the email
"sara@hussotech.com", print the part before the@and the part after it. - Print a small receipt with three lines, aligning the prices to the right with the width format.
- Write a Windows path to your desktop using a verbatim string.
string first = "Ayesha";
string last = "Khan";
int items = 3;
decimal price = 249.5m;
// Interpolation
Console.WriteLine($"Hello, {first} {last}!");
Console.WriteLine($"{items} items cost {items * price:F2} rupees");
// Formatting inside the braces
Console.WriteLine($"Price: {price,10:N2}|");
Console.WriteLine($"Today: {DateTime.Now:yyyy-MM-dd}");
// Useful methods
string email = " Ayesha.Khan@Example.com ";
string clean = email.Trim().ToLower();
Console.WriteLine(clean);
Console.WriteLine(clean.Length);
Console.WriteLine(clean.Contains("example"));
Console.WriteLine(clean.StartsWith("ayesha"));
Console.WriteLine(clean.Replace("example", "mail"));
Console.WriteLine(clean.IndexOf('@'));
string user = clean.Substring(0, clean.IndexOf('@'));
Console.WriteLine(user);
string[] parts = "red,green,blue".Split(',');
Console.WriteLine(parts.Length);
Console.WriteLine(string.Join(" | ", parts));
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account