How to remove characters from a string using Remove() in C#

Removing characters in C# can be done through the Remove() method. It removes characters in a string and returns a new string without the removed characters.

If a length is not specified, it removes all the characters from the beginning index until the end. If a length is specified, then it will only remove characters starting from the index specified, to the given length.

Syntax

str.Remove(index)
or
str.Remove(index, length)

Parameters

  • str: This is the string that calls the Remove() method.

  • index: This is the index position of characters to start deletion from. It is an integer value.

  • length: This is the length of characters to delete.

Return value

The value returned is a new string without the removed characters.

Code example

In the code example below, we will create strings and remove all the characters from the specified index until the end of the string using the Remove() method.

// create a class
class CharRemover
{
// creat main method
static void Main()
{
// create strings
string s1 = "Educative";
string s2 = "Theodore";
// remove some characters
string s3 = s1.Remove(3); // from 4th character
string s4 = s2.Remove(1); // from 2nd character
// log out values to console
System.Console.WriteLine(s3);
System.Console.WriteLine(s4);
}
}

We saw that all the characters from index 3 until the end were removed from s1. Similarly, all the characters from index 1 until the end were removed from s2.

As said earlier, when the length parameter is passed, we can then expect the characters to be removed to have a number. The length determines how many characters to remove, starting from the index specified.

See the example below:

// create class
class CharRemover
{
// create main method
static void Main()
{
// create strings
string s1 = "Educative";
// remove some characters
// remove from the 4th character
// but remove just 2
string s2 = s1.Remove(3, 2);
// print returned value
System.Console.WriteLine(s2);
}
}

In the code above, we specified length. The characters were removed, beginning from the fourth character to the specified length, which was two.

Free Resources