Search⌘ K
AI Features

Modifying Strings: Inserting, Deleting, and Replacing Characters

Understand how to modify immutable strings in C# by inserting, deleting, and replacing characters or substrings. Learn methods like converting strings to lists or char arrays, using Substring and concatenation, and applying built-in Replace. Gain insight into the time complexity of each operation and how to perform efficient string manipulations essential for algorithms and real applications.

By now you have established the understanding that strings in C# are immutable and that every operation which appears to modify a string is actually producing a new one. That raises a practical question that needs a direct answer: if strings cannot be changed in place, how does one actually perform the kinds of modifications that real programs and algorithms constantly require? Inserting a character at a specific position, removing an unwanted character, replacing one substring with another, these are fundamental operations, and understanding how to perform them correctly and efficiently is what we’ll learn now.

Inserting a character

Inserting a character at a specific position means placing a new character at a given index and shifting every character from that position onward one step to the right to accommodate it.

Consider the string "helo" and the requirement to insert the character 'l' at index 3.

Before: h e l o
Index: 0 1 2 3
After: h e l l o
Index: 0 1 2 3 4

The character 'o' that was at index 3 has moved to index 4 to make room for the inserted character. In general, inserting at position ii requires shifting every character from index ii to the end of the string one position to the right. In the worst case, inserting at the beginning of the string requires shifting all nn existing characters, making insertion an O(n)O(n) operation.

Insertion method 1

In C#, since strings are immutable, one option is to convert the string to a List<char>, perform the insertion on the list, and then build a new string from the characters. The Insert(i, x) method places the element x at index i, shifting all subsequent elements one position to the right.

C# 14.0
using System;
using System.Collections.Generic;
class Solution
{
static void Main()
{
string s = "helo";
List<char> chars = new List<char>(s.ToCharArray());
chars.Insert(3, 'l');
string result = new string(chars.ToArray());
Console.WriteLine($"Original string: \"{s}\"\n"); // Original string: helo
Console.WriteLine($"After insertion: \"{result}\""); // After insertion: hello
}
}

The list conversion costs O(n)O(n) ...