Tutorials / C# for Beginners / Working with strings and interpolation

Working with strings and interpolation

13 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. 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, Replace and friends.
  • Forgetting the $ and seeing {name} printed literally.
  • Calling Substring with a bad index. It throws ArgumentOutOfRangeException.
  • Using + in a big loop. Use StringBuilder or string.Join.

Try it yourself

  1. Store the text " Learn C# Step By Step " in a variable. Print it trimmed, in uppercase, and with its length before and after trimming.
  2. Given the email "sara@hussotech.com", print the part before the @ and the part after it.
  3. Print a small receipt with three lines, aligning the prices to the right with the width format.
  4. Write a Windows path to your desktop using a verbatim string.
csharp
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