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.
str.Remove(index)
or
str.Remove(index, length)
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.
The value returned is a new string without the removed characters.
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 classclass CharRemover{// creat main methodstatic void Main(){// create stringsstring s1 = "Educative";string s2 = "Theodore";// remove some charactersstring s3 = s1.Remove(3); // from 4th characterstring s4 = s2.Remove(1); // from 2nd character// log out values to consoleSystem.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 classclass CharRemover{// create main methodstatic void Main(){// create stringsstring s1 = "Educative";// remove some characters// remove from the 4th character// but remove just 2string s2 = s1.Remove(3, 2);// print returned valueSystem.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.