Chapter 5: Strings and String Manipulation
1. What is a String in C#? (Super Simple Explanation)
A string is just a sequence of characters (letters, numbers, symbols, spaces…).
Examples:
- “Hello”
- “Webliance from Hyderabad”
- “12345”
- “user@example.com”
- “” (empty string)
Important facts about strings in C#:
- Strings are immutable → once created, you cannot change them! (Every time you “modify” a string, C# actually creates a new string in memory.)
- Strings are reference types (like objects), not value types.
- They are stored in a special area called the string intern pool (helps save memory).
2. Creating Strings (Different Ways)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
string greeting = "Hello, World!"; // Most common string name = "Webliance"; string city = @"Hyderabad, Telangana, India"; // Verbatim string – ignores escape characters string multiLine = """ Line 1 Line 2 Line 3 """; // Raw string literal (C# 11+) string empty = ""; // Empty string string nullString = null; // null (no object at all) |
Verbatim strings (@) are super useful for file paths:
|
0 1 2 3 4 5 6 |
string path = @"C:\Users\Webliance\Documents\Code"; // No need for double backslashes! |
3. String Interpolation – The Modern & Beautiful Way ($””)
Introduced in C# 6 – this is the recommended way in 2026!
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var name = "Webliance"; var age = 25; var city = "Hyderabad"; // Old ugly way Console.WriteLine("Hello, my name is " + name + ", I am " + age + " years old and I live in " + city + "."); // Modern beautiful way Console.WriteLine($"Hello, my name is {name}, I am {age} years old and I live in {city}."); // Even better – expressions inside {} Console.WriteLine($"In 5 years I will be {age + 5} years old! 🎉"); Console.WriteLine($"Uppercase name: {name.ToUpper()}"); Console.WriteLine($"Length of name: {name.Length} characters"); |
Advanced formatting inside interpolation:
|
0 1 2 3 4 5 6 7 8 9 10 11 |
var salary = 75000.5678m; var today = DateTime.Now; Console.WriteLine($"Salary: {salary:C}"); // ₹75,000.57 (currency) Console.WriteLine($"Salary (2 decimals): {salary:F2}"); // 75000.57 Console.WriteLine($"Today is {today:dddd, MMMM dd, yyyy}"); // Wednesday, January 21, 2026 |
4. Most Important String Methods (You’ll Use These Every Day!)
| Method | What it does | Example | Result |
|---|---|---|---|
| Length | Number of characters | “Hello”.Length | 5 |
| ToUpper() / ToLower() | Convert case | “Webliance”.ToUpper() | “WEBLIANCE” |
| Trim() / TrimStart() / TrimEnd() | Remove whitespace | ” Hello “.Trim() | “Hello” |
| Substring(start, length) | Extract part of string | “Hello World”.Substring(6, 5) | “World” |
| Replace(old, new) | Replace all occurrences | “I love C#”.Replace(“C#”, “C# in 2026”) | “I love C# in 2026” |
| Split(separator) | Split into array | “a,b,c”.Split(‘,’) | [“a”, “b”, “c”] |
| IndexOf(text) | Find position (or -1 if not found) | “Hello World”.IndexOf(“World”) | 6 |
| Contains(text) | Check if contains | “Hello”.Contains(“ell”) | true |
| StartsWith() / EndsWith() | Check beginning/end | “file.txt”.EndsWith(“.txt”) | true |
| IsNullOrEmpty() | Check if null or empty (static method) | string.IsNullOrEmpty(“”) | true |
| IsNullOrWhiteSpace() | Null, empty or only spaces | string.IsNullOrWhiteSpace(” “) | true |
Real-life example – Cleaning user input:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Console.Write("Enter your full name: "); string input = Console.ReadLine(); string cleaned = input.Trim().ToLower(); Console.WriteLine($"Cleaned name: {cleaned}"); if (string.IsNullOrWhiteSpace(cleaned)) { Console.WriteLine("You didn't enter anything!"); } else if (cleaned.Contains("webliance")) { Console.WriteLine("Hey, that's my name! 😄"); } |
5. StringBuilder – For Performance When Building Large Strings
Because strings are immutable, doing this is very bad for performance:
|
0 1 2 3 4 5 6 7 8 9 10 |
string result = ""; for (int i = 0; i < 10000; i++) { result += i.ToString() + ", "; // Creates 10,000 new strings → slow & wastes memory! } |
Solution: Use StringBuilder
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using System.Text; // Don't forget this! var sb = new StringBuilder(); for (int i = 0; i < 10000; i++) { sb.Append(i); sb.Append(", "); } string final = sb.ToString(); // Only ONE string created at the end! Console.WriteLine(final); |
Handy StringBuilder methods:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var sb = new StringBuilder(); sb.Append("Hello"); // Add text sb.AppendLine("World!"); // Add text + newline sb.AppendFormat("Age: {0}", 25); // Like string.Format sb.Insert(0, "Dear "); // Insert at position sb.Replace("World", "C#!"); // Replace sb.Remove(5, 6); // Remove from index 5, 6 chars string result = sb.ToString(); |
Mini-Project: Smart Name Formatter
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
Console.WriteLine("=== Smart Name Formatter ===\n"); Console.Write("Enter your full name: "); var fullName = Console.ReadLine()?.Trim(); if (string.IsNullOrWhiteSpace(fullName)) { Console.WriteLine("No name entered!"); } else { var parts = fullName.Split(' ', StringSplitOptions.RemoveEmptyEntries); var firstName = parts[0]; var lastName = parts.Length > 1 ? parts[^1] : ""; // ^1 = last element var sb = new StringBuilder(); sb.AppendLine($"Original: {fullName}"); sb.AppendLine($"Uppercase: {fullName.ToUpper()}"); sb.AppendLine($"First name: {firstName}"); sb.AppendLine($"Last name: {lastName}"); sb.AppendLine($"Initials: {firstName[0]}{lastName[0]}".ToUpper()); sb.AppendLine($"Length: {fullName.Length} characters"); Console.WriteLine(sb.ToString()); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(); |
Your Homework (Fun & Practical!)
- Create a new console project called StringMaster
- Ask the user for:
- Their full name
- Their email
- A short bio (2–3 sentences)
- Then print a nice report using StringBuilder that includes:
- Name in uppercase
- Email in lowercase
- First 10 characters of bio
- Whether email contains “@”
- Number of words in bio
- A formatted greeting message
Next lesson: Control Flow (if, else, switch) – we’re going to make programs that make smart decisions!
You’re doing incredibly well! 🎉 Any part of strings confusing you? Want more examples? Just tell me — I’m right here for you! 💙
