C# String Remove() Method

www‮‬.theitroad.com

The Remove() method in C# is used to remove a specified number of characters from a string, starting from a specified position. The resulting string consists of the characters that were not removed.

The syntax of the Remove() method is as follows:

string.Remove(startIndex);

or

string.Remove(startIndex, count);

Here, startIndex is the zero-based index of the first character to remove, and count is the number of characters to remove. If count is not specified, the method removes all characters starting from the specified startIndex.

For example, to remove the first two characters from a string, you can use the following code:

string text = "Hello World";
string newText = text.Remove(0, 2);
Console.WriteLine(newText);  // Output: "llo World"

In this example, the Remove() method is used to remove the first two characters ("He") from the string "Hello World". The resulting string "llo World" is then assigned to the newText variable and printed to the console using the WriteLine() method.

You can also use the Remove() method to remove a single character from a string. For example, to remove the third character from a string, you can use the following code:

string text = "Hello";
string newText = text.Remove(2, 1);
Console.WriteLine(newText);  // Output: "Helo"

In this example, the Remove() method is used to remove the third character ("l") from the string "Hello". The resulting string "Helo" is then assigned to the newText variable and printed to the console.