Skip to content
Codewilds

Lesson 3 of 34 · Fundamentals

C# Strings and String Interpolation

easy10 XP3 min readFree lesson

Text is everywhere: names, messages, menus, log files. In C# text is stored in the string type, and the language gives you a superb tool for building it — string interpolation. In this lesson you will also meet the most useful string methods.

String interpolation

Put a $ in front of a string and you can drop any expression into it inside { }:

string hero = "Aria";
int level = 7;
Console.WriteLine($"{hero} reached level {level}!");   // Aria reached level 7!
Console.WriteLine($"Next level: {level + 1}");          // Next level: 8

That is much easier to read than hero + " reached level " + level + "!". After a colon you can add a format specifier:

double ratio = 0.756;
decimal price = 12.5m;
Console.WriteLine($"{price:F2}");   // 12.50   (2 decimal places)
Console.WriteLine($"{ratio:P1}");   // 75.6%   (percentage)
Console.WriteLine($"{1500000:N0}"); // 1,500,000
Console.WriteLine($"[{"left",-6}]"); // [left  ]  (pad to 6, left-aligned)

Escape sequences and verbatim strings

Some characters need a backslash: \n is a new line, \t a tab, \" a double quote and \\ a backslash. A verbatim string starts with @ and takes backslashes literally, which is handy for file paths:

Console.WriteLine("She said \"hi\"\nand left.");
string path = @"C:\games\citadel";

Useful string methods

A string knows a lot about itself:

string s = "  Sharpforge Citadel  ";
s.Length                       // 22 (spaces count)
s.Trim()                       // "Sharpforge Citadel"
s.Trim().ToUpper()             // "SHARPFORGE CITADEL"
s.Contains("forge")            // true
s.Trim().StartsWith("Sharp")   // true
s.Trim().IndexOf("Citadel")    // 11
s.Trim().Substring(0, 5)       // "Sharp" (start index, length)
s.Replace(" ", "")             // "SharpforgeCitadel"
"a,b,c".Split(',')             // ["a", "b", "c"]
string.Join("-", "a,b,c".Split(','))   // "a-b-c"

You can read single characters with an index — positions start at 0 — and ^1 counts from the end:

string word = "dragon";
char first = word[0];    // 'd'
char last = word[^1];    // 'n'

Strings are immutable

A string never changes after it is created. Methods like ToUpper return a new string; they do not modify the original:

string name = "aria";
name.ToUpper();             // result thrown away!
Console.WriteLine(name);    // aria
name = name.ToUpper();      // keep the result
Console.WriteLine(name);    // ARIA

Comparing strings with == compares their text, so "abc" == "abc" is true. To ignore case, use string.Equals(a, b, StringComparison.OrdinalIgnoreCase).

How these coding challenges work

From now on most challenges ask you to finish methods inside a class called Program, and hidden tests call them with different inputs. You will learn exactly how methods work in Chapter 2. For now: write your code between the braces of each method and hand back the answer with return:

public class Program
{
    public static string Shout(string text)
    {
        return text.ToUpper() + "!";
    }
}

Assignment

Complete four methods in Program:

  1. Greeting(name, level) returns "Welcome, <name>! You are level <level>." — e.g. Greeting("Aria", 7) returns "Welcome, Aria! You are level 7.".
  2. Initials(firstName, lastName) returns the uppercase first letters followed by dots: Initials("grace", "hopper") returns "G.H.".
  3. CleanTag(tag) trims spaces from both ends, lowercases the text and replaces the remaining spaces with dashes: CleanTag(" Dragon Slayer ") returns "dragon-slayer".
  4. PriceTag(item, price) returns the price with exactly two decimals: PriceTag("Sword", 12.5m) returns "Sword costs 12.50 gold".

Strings and formatting in other languages

Need a quick reminder? The C# cheat sheet has every topic of Learn C# on one page.

Lesson last updated on .

Write code ↓
C#+10 XP

Press Run to execute your code, or Submit to check it against the tests.