Strings

Intermediate 25 min read Lesson 8 of 13

What is a String?

A string is a sequence of characters. Think of it like a sentence, a word, or even a single letter. In C#, strings are used to store text.

Text
Stores words and sentences

Immutable
Cannot be changed once created

Everywhere
Used in almost every program

Think of it like this: A string is like a sentence written on a piece of paper. You can read it, copy it, or write a new sentence, but you can't erase or change the original paper! This is called "immutable" - once created, it cannot be changed.

Creating Strings

There are several ways to create a string in C#.

// ===== WAYS TO CREATE A STRING =====

// 1. Using double quotes (most common)
string name = "John Doe";

// 2. Empty string
string empty = "";                // Empty string
string empty2 = string.Empty;      // Same as "" (recommended)

// 3. Null string (no value)
string nullString = null;

// 4. Multi-line string (verbatim string)
string multiLine = @"This is a
multi-line string
with multiple lines.";

// 5. String interpolation (C# 6+) - BEST WAY!
int age = 25;
string message = $"Hello, I'm {age} years old.";

// 6. Using the string constructor
char[] chars = { 'H', 'e', 'l', 'l', 'o' };
string fromChars = new string(chars);  // "Hello"
Pro Tip: Use string interpolation ($"Hello {name}") for most strings - it's the cleanest and most readable way!

String Concatenation (Joining Strings)

Concatenation means joining two or more strings together. Think of it like connecting pieces of a train.

// ===== DIFFERENT WAYS TO JOIN STRINGS =====

string first = "Hello";
string second = "World";

// 1. Using + operator (simple and common)
string combined1 = first + " " + second;  // "Hello World"

// 2. Using string.Concat()
string combined2 = string.Concat(first, " ", second);  // "Hello World"

// 3. Using interpolation (CLEANEST)
string combined3 = $"{first} {second}";  // "Hello World"

// 4. Joining a list of strings
string[] words = { "Hello", "from", "C#" };
string joined = string.Join(" ", words);  // "Hello from C#"

// ===== REAL-WORLD EXAMPLE: Building a full name =====
string firstName = "John";
string lastName = "Smith";
string fullName = $"{firstName} {lastName}";  // "John Smith"
Important! Remember that strings are immutable. When you concatenate, you're creating a new string, not changing the old one.

Common String Methods

Strings have many built-in methods that let you manipulate text. Here are the most useful ones.

// ===== LENGTH =====
string text = "Hello World";
int length = text.Length;  // 11

// ===== CASE CONVERSION =====
string upper = text.ToUpper();  // "HELLO WORLD"
string lower = text.ToLower();  // "hello world"

// ===== CHECKING CONTENT =====
bool containsWorld = text.Contains("World");       // true
bool startsWithHello = text.StartsWith("Hello");  // true
bool endsWithWorld = text.EndsWith("World");    // true

// ===== FINDING POSITION =====
int indexOfWorld = text.IndexOf("World");  // 6
int indexOfX = text.IndexOf("x");         // -1 (not found)

// ===== GETTING A PART (SUBSTRING) =====
string sub1 = text.Substring(6);       // "World" (from index 6 to end)
string sub2 = text.Substring(0, 5);  // "Hello" (5 characters from index 0)

// ===== SPLITTING =====
string data = "apple,banana,orange";
string[] parts = data.Split(',');  // ["apple", "banana", "orange"]

// ===== REPLACING =====
string replaced = text.Replace("World", "C#");  // "Hello C#"

// ===== TRIMMING (REMOVING SPACES) =====
string messy = "  Hello World  ";
string trimmed = messy.Trim();   // "Hello World"
string trimStart = messy.TrimStart();  // "Hello World  "
string trimEnd = messy.TrimEnd();    // "  Hello World"
Method Description Example
Length Gets the number of characters "Hello".Length // 5
ToUpper() Converts to uppercase "Hello".ToUpper() // "HELLO"
ToLower() Converts to lowercase "Hello".ToLower() // "hello"
Contains() Checks if a substring exists "Hello".Contains("el") // true
IndexOf() Finds the position of a substring "Hello".IndexOf("l") // 2
Substring() Extracts part of a string "Hello".Substring(1, 3) // "ell"
Replace() Replaces occurrences "Hello".Replace("l", "x") // "Hexxo"
Split() Splits into an array "a,b,c".Split(',') // ["a","b","c"]
Trim() Removes leading/trailing spaces " Hello ".Trim() // "Hello"
Join() Joins an array into a string string.Join(",", new[]{"a","b"}) // "a,b"

String Formatting

Formatting lets you control how text looks - like showing currency, dates, or numbers in a specific way.

// ===== STRING INTERPOLATION (BEST WAY) =====
string name = "Alice";
int age = 30;
string info = $"Name: {name}, Age: {age}";  // "Name: Alice, Age: 30"

// ===== FORMATTING NUMBERS =====
decimal price = 19.99m;
string currency = $"Price: {price:C}";        // "Price: $19.99" (currency)
string percent = $"Discount: {0.15:P}";        // "Discount: 15.00%"
string number = $"Number: {12345.6789:N2}";  // "Number: 12,345.68"
string fixedNum = $"Value: {42:D5}";          // "Value: 00042"

// ===== FORMATTING DATES =====
DateTime today = DateTime.Now;
string shortDate = $"Today: {today:d}";     // "01/15/2024"
string longDate = $"Today: {today:D}";       // "Monday, January 15, 2024"
string time = $"Time: {today:t}";           // "2:30 PM"
string full = $"Now: {today:F}";            // "Monday, January 15, 2024 2:30:45 PM"

// ===== STRING.PADLEFT / PADRIGHT =====
string id = "42";
string padded = id.PadLeft(5, '0');  // "00042"
string rightPadded = id.PadRight(5, '*'); // "42***"
Pro Tip: String interpolation ($"...") is the best way to format strings. It's clean, readable, and powerful!

StringBuilder - For Heavy String Manipulation

StringBuilder is used when you need to modify a string many times. Remember, strings are immutable - every change creates a new string. StringBuilder is like a whiteboard - you can write, erase, and rewrite without creating new ones!

// ===== WHEN TO USE STRINGBUILDER =====
// BAD: Creating many new strings in a loop
string result = "";
for (int i = 0; i < 1000; i++)
{
    result += "x";  // Creates 1000 new strings!
}

// GOOD: Using StringBuilder
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
    sb.Append("x");  // Much more efficient!
}
string result2 = sb.ToString();

// ===== STRINGBUILDER METHODS =====
var builder = new StringBuilder();

// Add text
builder.Append("Hello");
builder.Append(" ");
builder.Append("World");  // "Hello World"

// Insert at a position
builder.Insert(6, "Beautiful ");  // "Hello Beautiful World"

// Remove characters
builder.Remove(6, 10);  // Removes "Beautiful "

// Replace text
builder.Replace("World", "C#");  // "Hello C#"

// Clear
builder.Clear();  // Removes all text

// ===== REAL-WORLD EXAMPLE: Building HTML =====
var html = new StringBuilder();
html.AppendLine("<div>");
html.AppendLine("<h1>Welcome</h1>");
html.AppendLine("<p>Hello World</p>");
html.AppendLine("</div>");
string htmlString = html.ToString();
When to use StringBuilder: Use it when you need to modify a string many times (like in a loop). For simple cases, regular strings are fine!

String vs StringBuilder

Feature String StringBuilder
Mutability Immutable (cannot change) Mutable (can change)
Performance Good for small operations Better for many operations
Memory Usage Creates new objects Reuses the same object
When to Use When you create a string once When you modify many times
Examples string name = "John"; var sb = new StringBuilder();

Real-World Examples

📝 Validating User Input
string input = "  John  ";
string clean = input.Trim();
if (string.IsNullOrEmpty(clean))
    Console.WriteLine("Please enter a name");
💳 Formatting Credit Card
string card = "1234567812345678";
string formatted = string.Join(" ", 
    card.Chunk(4).Select(c => new string(c)));
// "1234 5678 1234 5678"
📧 Validating Email
string email = "user@example.com";
bool isValid = email.Contains("@") && 
    email.Contains(".") && 
    email.Length > 5;
📊 Generating CSV
var data = new[] { "John", "25", "Engineer" };
string csv = string.Join(",", data);
// "John,25,Engineer"

Exercise: Text Analyzer

Task: Create a program that analyzes text using string methods.

Instructions:
  1. Create a console application called "TextAnalyzer"
  2. Ask the user to enter a sentence
  3. Analyze the text and display:
    • Total number of characters
    • Total number of words
    • Total number of vowels
    • Text in uppercase
    • Text in lowercase
    • The first 10 characters
    • Whether the text contains the word "C#"
  4. Use at least 6 different string methods
  5. Use string interpolation for all output
Hints:
  • Use Console.ReadLine() to get user input
  • Use Split() to count words
  • Use ToLower() and Count() to count vowels
  • Use Substring() to get first 10 characters
  • Use Contains() to check for "C#"
Expected Output:
Enter a sentence: I love learning C# programming!
--- Text Analysis ---
Characters: 31
Words: 5
Vowels: 9
Uppercase: I LOVE LEARNING C# PROGRAMMING!
Lowercase: i love learning c# programming!
First 10 chars: I love lea
Contains "C#": True
Key Takeaway

Strings are everywhere in C#. Remember these key points:

✅ Strings are immutable - every change creates a new string
✅ Use string interpolation ($"...") for clean formatting
✅ Use StringBuilder when modifying strings many times
✅ Master the common methods: Length, Substring, Split, Replace, Contains, Trim
✅ Always check for null or empty strings before using them

Test Your Knowledge - Take Quiz