Strings, input and output
Read input from the user, build text with interpolation, and use the most important string methods.
string, a sequence of characters.
Reading input
Console.Write("What is your name? ");string? name = Console.ReadLine(); // waits until Enter is pressedConsole.WriteLine("Hello, " + name + "!"); Output
What is your name? Ravi Hello, Ravi!
Building strings
string first = "Ravi";int age = 25; string a = "Name: " + first + ", age " + age; // concatenationstring b = $"Name: {first}, age {age}"; // interpolation (preferred)string c = $"Next year: {age + 1}"; // any expression in { }string d = $"Price: {1499.5:F2}"; // format: 2 decimals Console.WriteLine(b);Console.WriteLine(d); Output
Name: Ravi, age 25 Price: 1499.50
Escape sequences and verbatim strings
| Write | To get |
|---|---|
\n | |
\t | |
\" | |
\\ |
Console.WriteLine("Line 1\nLine 2");Console.WriteLine("She said \"Hi\"");string path = @"C:\Projects\Steel\model.ifc"; // @ = verbatim: \ is literalConsole.WriteLine(path); Output
Line 1 Line 2 She said "Hi" C:\Projects\Steel\model.ifc
Inside a string: indexes and methods
| Member | What it does |
|---|---|
s.Length | |
s[i] | i (a char) |
s.ToUpper() / s.ToLower() | |
s.Trim() | |
s.Contains(x) | true if x appears in s |
s.IndexOf(x) | x, or -1 |
s.Substring(start, length) | |
s.Replace(a, b) | a with b |
s.Split(sep) | string[] |
string.IsNullOrWhiteSpace(s) |
Comparing strings
string a = "Steel";string b = "steel"; Console.WriteLine(a == b); // FalseConsole.WriteLine(a.Equals(b, StringComparison.OrdinalIgnoreCase)); // True Output
False True
Practice
Show the solution
Console.Write("Full name: ");string name = (Console.ReadLine() ?? "").Trim(); Console.WriteLine(name.ToUpper());Console.WriteLine($"Length: {name.Length}");if (name.Length > 0) Console.WriteLine($"First letter: {name[0]}"); Output
Full name: ravi selva RAVI SELVA Length: 10 First letter: r
Remember
Console.ReadLine()returns a string; convert it for numbers.Prefer interpolation: $"Hello {name}", with formats like{x:F2}.Indexes start at 0; the last index is Length - 1.Strings are immutable: store the result of ToUpper,Trim,Replace…