C# `String.Remove()` Method: Removing Characters from Strings

Learn how to efficiently remove characters from strings in C# using the `String.Remove()` method. This tutorial explains its different overloads, demonstrates its usage with code examples, and highlights its application in various string manipulation and text processing tasks.



Removing Characters from Strings in C# using `String.Remove()`

Understanding `String.Remove()`

The C# `Remove()` method creates a new string by removing characters from an existing string. The original string remains unchanged; a new string with the specified characters removed is returned. This method is frequently used to modify strings, extracting specific parts or eliminating unwanted sections. The `Remove()` method is case-sensitive.

`String.Remove()` Method Signatures

The `Remove()` method has two main versions:

  • public string Remove(int startIndex);: Removes all characters from the specified `startIndex` to the end of the string.
  • public string Remove(int startIndex, int count);: Removes a specified number of characters (`count`), starting at the `startIndex`.

Examples: Using `String.Remove()`

Example 1: Removing Characters from a Specific Index

This example removes all characters from index 2 onwards.

C# Code

using System;

public class StringRemoveExample {
    public static void Main(string[] args) {
        string str = "Hello C#";
        string newStr = str.Remove(2);
        Console.WriteLine(newStr); // Output: He
    }
}

Example 2: Removing a Specific Number of Characters

This example removes 5 characters, starting at index 4.

C# Code

using System;

public class StringRemoveExample {
    public static void Main(string[] args) {
        string str = "abcdefghijk";
        string newStr = str.Remove(4, 5);
        Console.WriteLine(newStr); // Output: abcdjk
    }
}

Conclusion

The `Remove()` method is a fundamental string manipulation function in C#. It offers flexibility in removing parts of a string, but always remember that it creates a *new* string, leaving the original string unchanged. Handle potential `ArgumentOutOfRangeException` errors appropriately.