Strings & StringBuilder - Textnotes

Strings & StringBuilder


Strings are sequences of characters. C# provides powerful tools for string manipulation, comparison, and formatting.

1. String Manipulation

Strings are immutable in C# (cannot be changed once created).


string name = "John Doe";
Console.WriteLine("Original: " + name);

// Convert to uppercase and lowercase
Console.WriteLine(name.ToUpper()); // JOHN DOE
Console.WriteLine(name.ToLower()); // john doe

// Trim whitespace
string str = " Hello World ";
Console.WriteLine(str.Trim()); // "Hello World"

2. Common String Methods

MethodDescriptionExample
LengthReturns length of string"Hello".Length → 5
Substring(start, len)Extracts substring"Hello".Substring(1, 3) → "ell"
IndexOf(char/string)Finds index of first occurrence"Hello".IndexOf('l') → 2
LastIndexOf(char)Finds index of last occurrence"Hello".LastIndexOf('l') → 3
Replace(old, new)Replaces characters or words"Hello".Replace('l','x') → "Hexxo"
Contains(value)Checks if string contains value"Hello".Contains("ll") → true
StartsWith(value)Checks start of string"Hello".StartsWith("He") → true
EndsWith(value)Checks end of string"Hello".EndsWith("lo") → true
Split(separator)Splits string into array"a,b,c".Split(',') → ["a","b","c"]
Insert(index, string)Inserts string at specified index"Hello".Insert(1,"123") → "H123ello"
Remove(start, count)Removes characters"Hello".Remove(1,3) → "Ho"

Example:


string message = "Hello World";
Console.WriteLine(message.Substring(6)); // "World"
Console.WriteLine(message.Replace("World","C#")); // "Hello C#"
Console.WriteLine(message.IndexOf('o')); // 4

3. String Interpolation

Easier way to combine strings with variables using $.


string name = "John";
int age = 25;
Console.WriteLine($"Name: {name}, Age: {age}"); // Name: John, Age: 25

Alternative:


Console.WriteLine("Name: " + name + ", Age: " + age);

4. StringBuilder Class

StringBuilder is mutable and efficient for multiple modifications.


using System.Text;

StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World"); // Add at end
sb.Insert(6, "C# "); // Insert string
sb.Replace("Hello","Hi"); // Replace string

Console.WriteLine(sb); // Hi C# World

Common Methods of StringBuilder:

  1. Append() → Add text at end
  2. Insert(index, string) → Insert text at index
  3. Remove(start, length) → Remove part of string
  4. Replace(old, new) → Replace substring
  5. Clear() → Remove all content

5. Comparing Strings

Strings can be compared using ==, Equals(), or CompareTo().


string s1 = "Hello";
string s2 = "hello";

Console.WriteLine(s1 == s2); // False (case-sensitive)
Console.WriteLine(s1.Equals(s2, StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(s1.CompareTo(s2)); // Returns -1, 0, or 1

Explanation:

  1. == → Compares values
  2. Equals() → Can ignore case
  3. CompareTo() → Returns integer:
  4. 0 → equal
  5. <0 → s1 < s2
0 → s1 > s2

6. Formatting Strings

C# provides multiple ways to format strings.

6.1 Composite Formatting


string name = "John";
int age = 25;
Console.WriteLine("Name: {0}, Age: {1}", name, age);

6.2 String Interpolation


Console.WriteLine($"Name: {name}, Age: {age}");

6.3 String.Format


string result = string.Format("Name: {0}, Age: {1}", name, age);
Console.WriteLine(result);

6.4 Padding & Alignment


Console.WriteLine("{0,-10} {1,5}", "Name", "Age"); // Align columns

Summary of Chapter 7:

  1. Strings are immutable; StringBuilder is mutable.
  2. String methods help manipulation, searching, and slicing.
  3. String interpolation and formatting simplify output.
  4. String comparison can be case-sensitive or insensitive.
  5. StringBuilder is efficient for frequent modifications.