String.Remove() method removes a given number of characters from a string at a specified position. The position is a 0 index position. That means, the 0th position is the first character in the string.
In C#, Strings are immutable. That means, the method does not remove characters from a string. The method creates and returns a new string without those characters.
String.Remove() method has two overloaded forms.
Method | Description |
Remove(Int32) | Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted. |
Remove(Int32, Int32) | Returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted. |
Example 1
The following example removes all characters from a string that are after 25th position in the string.
- string founder = "Mahesh Chand is a founder of C# Corner";
-
- string first25 = founder.Remove(25);
- Console.WriteLine(first25);
The following example removes 12 characters from the 10th position in the string.
-
- String newStr = founder.Remove(10, 12);
- Console.WriteLine(newStr);
Example 2
Now, let’s say you want to delete everything after or before a substring in a string. We can use String.IndexOf() to find the position of the substring and can use starting index and number of characters to remove.
The following example removes everything before and after substring ‘founder’ in a string.
-
- int pos = founder.IndexOf("founder");
- if (pos >= 0)
- {
-
- string afterFounder = founder.Remove(pos);
- Console.WriteLine(afterFounder);
-
- string beforeFounder = founder.Remove(0, pos);
- Console.Write(beforeFounder);
- }
The complete program is listed in Listing 1.
- using System;
- namespace RemoveStringSample
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- string founder = "Mahesh Chand is a founder of C# Corner";
-
- string first25 = founder.Remove(25);
- Console.WriteLine(first25);
-
- String newStr = founder.Remove(10, 12);
- Console.WriteLine(newStr);
- int pos = founder.IndexOf("founder");
- if (pos >= 0)
- {
-
- string afterFounder = founder.Remove(pos);
- Console.WriteLine(afterFounder);
-
- string beforeFounder = founder.Remove(0, pos);
- Console.Write(beforeFounder);
- }
- Console.ReadKey();
- }
- }
- }
Listing 1.