string.Substring() / Remove()
The Substring() method extracts a portion of a string, and the Remove() method returns a new string with the specified range of characters deleted.
Syntax
// Extracts from startIndex to the end of the string. string.Substring(int startIndex) // Extracts length characters starting from startIndex. string.Substring(int startIndex, int length) // Returns the string with everything from startIndex to the end removed. string.Remove(int startIndex) // Returns the string with count characters removed starting from startIndex. string.Remove(int startIndex, int count)
Method List
| Method | Description |
|---|---|
| Substring(int startIndex) | Returns the substring from startIndex to the end of the string. |
| Substring(int startIndex, int length) | Returns a substring of length characters starting from startIndex. |
| Remove(int startIndex) | Returns the string with all characters from startIndex onward removed. |
| Remove(int startIndex, int count) | Returns the string with count characters removed starting from startIndex. |
Sample Code
using System;
string message = "Hello, C# World!";
// Extract with Substring().
Console.WriteLine(message.Substring(7)); // C# World!
Console.WriteLine(message.Substring(7, 2)); // C#
// Delete with Remove().
Console.WriteLine(message.Remove(7)); // Hello,
Console.WriteLine(message.Remove(7, 3)); // Hello, World!
// Example combining with IndexOf().
string email = "user@example.com";
int atIndex = email.IndexOf("@");
string userName = email.Substring(0, atIndex);
string domain = email.Substring(atIndex + 1);
Console.WriteLine(userName); // user
Console.WriteLine(domain); // example.com
// The original string is not modified.
Console.WriteLine(message); // Hello, C# World!
Notes
C# strings are immutable. Neither Substring() nor Remove() modifies the original string — both always return a new string.
If the index is out of range, an ArgumentOutOfRangeException is thrown. It is safer to verify the index first using Length / IndexOf() before calling these methods.
For replacing substrings or checking whether a string contains another, see Replace() / Contains().
If you find any errors or copyright issues, please contact us.