← Retour au cours: C# from scratch

Strings, interpolation and text methods

Vidéo bientôt disponible

A string is a sequence of characters: names, messages, addresses, almost any data a person reads. In C#, strings are immutable, which means they are never modified in place: every operation that seems to change them returns a new string. This explains a very common mistake: writing name.ToUpper() without saving the result does not change name. You must assign the returned value to a variable.

Interpolation with $

The modern way to build text with values is interpolation: you put $ before the quotes and write variables between braces. It is much more readable than joining pieces with +. Inside the braces you can put any expression, and after a colon a format: N2 for two decimals with thousands separator, C for currency, P for percentage, or 0000 to pad with zeros. With a comma you align the value to a fixed width, useful for tables in the console. If you need a literal brace, double it: {{ and }}.

csharp
using System.Globalization;
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; // same output on every PC

string name = "Ana";
int age = 29;
decimal price = 1234.5m;
double ratio = 0.256;

Console.WriteLine("Hi " + name + ", you are " + age);   // old way
Console.WriteLine($"Hi {name}, you are {age}");          // interpolation
Console.WriteLine($"Price: {price:N2}");                 // 1,234.50
Console.WriteLine($"Ratio: {ratio:P1}");                 // 25.6 %
Console.WriteLine($"Order: {7:0000}");                   // 0007
Console.WriteLine($"[{name,6}] [{name,-6}]");            // right and left aligned
Console.WriteLine($"Sum: {age + 1}, braces: {{ok}}");    // expression and literal braces

Useful string methods

Strings have dozens of methods. The ones you will use most are: Length (a property, how many characters), ToUpper and ToLower, Trim to remove spaces at the ends, Contains, StartsWith and EndsWith to ask questions, IndexOf to find a position (it returns -1 if not found), Replace to substitute, Substring to extract a piece and Split to divide into parts. Each character has an index that starts at 0, so name[0] is the first letter. Accessing an index that does not exist causes a runtime error, so check Length first.

csharp
string text = "  Learn C# step by step  ";
string clean = text.Trim();

Console.WriteLine(clean.Length);              // 21
Console.WriteLine(clean.ToUpper());           // LEARN C# STEP BY STEP
Console.WriteLine(clean.Contains("step"));    // True
Console.WriteLine(clean.StartsWith("Learn")); // True
Console.WriteLine(clean.IndexOf("C#"));       // 6
Console.WriteLine(clean.Replace("step", "STEP")); // Learn C# STEP by STEP
Console.WriteLine(clean.Substring(6, 2));     // C#
Console.WriteLine(clean[0]);                  // L

string[] words = clean.Split(' ');
Console.WriteLine(words.Length);              // 5
Console.WriteLine(string.Join("-", words));   // Learn-C#-step-by-step

text.ToUpper();                               // useless: result is discarded
Console.WriteLine(text.Trim() == clean);      // True

Long text and special characters

Inside a string, the backslash starts a special sequence: \n is a line break, \t a tab, \" a quote and \\ a backslash. For Windows paths, doubling every backslash is annoying, so there is the string literal with @ in front, where the backslash is normal. Since C# 11 you also have raw string literals with three quotes, which let you write several lines and quotes without escaping, ideal for JSON or long text. If you build text inside a loop from many pieces, use StringBuilder: it avoids creating a new string at every step.

csharp
using System.Text;

Console.WriteLine("Name:\tAna\nCity:\tLima");
Console.WriteLine("She said \"hi\"");
Console.WriteLine(@"C:\Users\Ana\notes.txt");

string json = """
    {
      "name": "Ana",
      "age": 29
    }
    """;
Console.WriteLine(json);

var sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
    sb.Append(i).Append(' ');
}
Console.WriteLine(sb.ToString().Trim()); // 1 2 3 4 5

Testez vos acquis

Question 1 sur 2

What does name.ToUpper() do if you do not save the result?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →