Strings

Loading concept...

🎸 C# Strings: Your Magic Necklace of Characters

Imagine you have a necklace. Each bead on the necklace is a letter or symbol. When you string them together, you get words and sentences!

In C#, a string is exactly like that necklace—a collection of characters strung together.


🌟 What is a String?

A string is text. It’s how your computer stores words, sentences, and messages.

string greeting = "Hello!";
string name = "Emma";

Think of it like writing on a piece of paper. The paper holds your message!


🎨 String Interpolation: Fill in the Blanks!

Remember Mad Libs? You fill in blanks to create funny sentences.

String interpolation lets you put variables inside your text. Just use a $ before the quotes and {} around your variables.

string name = "Alex";
int age = 10;

string message = quot;Hi, I'm {name}!";
// Result: "Hi, I'm Alex!"

string intro = quot;{name} is {age} years old.";
// Result: "Alex is 10 years old."

Why is this cool?

  • No messy + signs everywhere
  • Easy to read
  • You can even do math inside!
int apples = 3;
int oranges = 5;
string total = quot;Total fruits: {apples + oranges}";
// Result: "Total fruits: 8"

🚪 Escape Strings: Secret Codes!

Sometimes you need special characters in your text:

  • A new line (like pressing Enter)
  • A tab (like pressing Tab)
  • Quote marks inside quotes

These are escape sequences. They start with a backslash \.

Code What it does Example
\n New line Line 1\nLine 2
\t Tab space Hello\tWorld
\" Quote mark Say \"Hi\"
\\ Backslash C:\\Users
string poem = "Roses are red,\nViolets are blue.";
// Output:
// Roses are red,
// Violets are blue.

string path = "C:\\Users\\Documents";
// Output: C:\Users\Documents

📜 Verbatim Strings: What You See is What You Get!

Tired of typing \\ for every backslash? Use verbatim strings with @ before the quotes.

// Regular string (escape needed)
string path1 = "C:\\Users\\Desktop\\file.txt";

// Verbatim string (no escaping!)
string path2 = @"C:\Users\Desktop\file.txt";
// Both give: C:\Users\Desktop\file.txt

Multi-line text becomes easy!

string poem = @"Roses are red,
Violets are blue,
C# is awesome,
And so are you!";

No \n needed. Just write naturally!

Tip: To put a quote inside a verbatim string, use two quotes: ""

string quote = @"She said ""Hello!""";
// Output: She said "Hello!"

✨ Raw String Literals: The Ultimate Freedom!

C# 11 introduced raw strings. They use three or more quotes.

string json = """
    {
        "name": "Emma",
        "age": 10
    }
    """;

Why raw strings are magical:

  1. No escaping needed—ever!
  2. Quotes work naturally
  3. Perfect for JSON, HTML, or any complex text
  4. Indentation is handled smartly
string html = """
    <div>
        <p>Hello World!</p>
    </div>
    """;

🧊 String Immutability: The Ice Sculpture

Here’s a big secret about strings: they cannot be changed!

Think of a string like an ice sculpture. Once it’s carved, you can’t change it. If you want something different, you must create a new sculpture.

string word = "Hello";
word = word + " World";
// This creates a NEW string!
// The old "Hello" still exists
// (until the computer cleans it up)
graph TD A["word = 'Hello'"] --> B["Memory: 'Hello'"] C["word = word + ' World'"] --> D["Memory: 'Hello World'"] B --> E["Old 'Hello' abandoned"]

Why does this matter?

If you change strings a lot in a loop, you’re creating MANY ice sculptures. This wastes memory and time!

// SLOW - creates 100 strings!
string result = "";
for (int i = 0; i < 100; i++)
{
    result = result + i;  // New string each time!
}

🔧 String Methods: Your Toolbox

Strings come with built-in tools. Here are the most useful ones:

Length - How long is it?

string name = "Emma";
int length = name.Length;  // 4

ToUpper() & ToLower() - Change case

string shout = "hello".ToUpper();  // "HELLO"
string whisper = "HELLO".ToLower(); // "hello"

Trim() - Remove extra spaces

string messy = "  hello  ";
string clean = messy.Trim();  // "hello"

Contains() - Is it there?

string sentence = "I love pizza";
bool hasPizza = sentence.Contains("pizza"); // true
bool hasCake = sentence.Contains("cake");   // false

Replace() - Swap words

string old = "I like cats";
string news = old.Replace("cats", "dogs");
// "I like dogs"

Split() - Break it apart

string fruits = "apple,banana,cherry";
string[] list = fruits.Split(',');
// ["apple", "banana", "cherry"]

Substring() - Take a piece

string word = "Hamburger";
string part = word.Substring(0, 3);  // "Ham"
string end = word.Substring(3);      // "burger"

StartsWith() & EndsWith()

string file = "photo.jpg";
bool isJpg = file.EndsWith(".jpg");     // true
bool isPhoto = file.StartsWith("photo"); // true

🏗️ StringBuilder: The LEGO Builder

Remember the ice sculpture problem? StringBuilder is the solution!

Think of StringBuilder like LEGO blocks. You can keep adding and removing pieces without starting over.

using System.Text;

StringBuilder builder = new StringBuilder();
builder.Append("Hello");
builder.Append(" ");
builder.Append("World");

string result = builder.ToString();
// "Hello World"

When to use StringBuilder?

Use String Use StringBuilder
Few changes Many changes
Simple text Loops that build text
Small strings Large text creation

StringBuilder in action:

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
    sb.AppendLine(quot;Line {i}");
}
string result = sb.ToString();
// Line 1
// Line 2
// Line 3
// Line 4
// Line 5

Useful StringBuilder methods:

StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World");     // Add to end
sb.Insert(0, "Say: ");   // Insert at position
sb.Replace("World", "C#"); // Replace text
sb.Clear();              // Empty it

🎯 String Formatting: Pretty Printing

Sometimes you need your numbers and dates to look nice.

Composite Formatting

string message = string.Format(
    "Hello {0}, you have {1} points",
    "Alex", 100
);
// "Hello Alex, you have 100 points"

Number Formatting

double price = 19.99;
string money = quot;{price:C}";    // "$19.99"

int big = 1234567;
string num = quot;{big:N0}";       // "1,234,567"

double percent = 0.756;
string pct = quot;{percent:P0}";   // "76%"

Common Format Codes:

Code Meaning Example
C Currency $1,234.56
N Number with commas 1,234.56
P Percentage 75.60%
D4 Digits (pad zeros) 0042
F2 Fixed decimals 3.14

Alignment and Padding

string name = "Emma";
string left = quot;|{name,-10}|";  // "|Emma      |"
string right = quot;|{name,10}|";  // "|      Emma|"

Date Formatting

DateTime now = DateTime.Now;
string date = quot;{now:MM/dd/yyyy}";  // "12/03/2025"
string time = quot;{now:hh:mm tt}";    // "02:30 PM"
string full = quot;{now:MMMM d, yyyy}"; // "December 3, 2025"

🎭 Quick Summary

graph LR A[C# Strings] --> B[Creating] A --> C[Modifying] A --> D[Building] B --> B1["'Hello'"] B --> B2["