C# .Substring()
The C# .Substring() method is a built-in string method that extracts a portion of a string starting from a specified index position. It returns a new string containing the characters from the starting position to either the end of the string or for a specified length, without modifying the original string.
Syntax of C# .Substring()
public string Substring(int startIndex)
public string Substring(int startIndex, int length)
Parameters:
startIndex: The zero-based starting position from where the substring begins. The type isSystem.Int32.length(optional): The number of characters to include in the substring. The type isSystem.Int32.
Return value:
Both methods return a new string (System.String) containing the extracted substring.
Exceptions:
The method throws ArgumentOutOfRangeException if:
startIndexis less than zero or greater than the length of the stringlengthis less than zerostartIndexpluslengthindicates a position not within the current string
Example 1: Basic Usage of .Substring()
This example demonstrates how to use the .Substring() method with a single parameter to extract characters from a specific position to the end of the string:
using System;public class Program{public static void Main(){string text = "Hello World";// Extract substring from index 6 to the endstring result = text.Substring(6);Console.WriteLine($"Original: {text}");Console.WriteLine($"Substring from index 6: {result}");}}
The output of this example will be:
Original: Hello WorldSubstring from index 6: World
This example extracts all characters starting from index 6 (the letter ‘W’) to the end of the string.
Example 2: Extract Characters with Length Using .Substring()
This example shows how to use the .Substring() method with both parameters to extract a specific number of characters:
using System;public class Program{public static void Main(){// Extract username (characters before @)int atIndex = email.IndexOf('@');string username = email.Substring(0, atIndex);// Extract domain (characters after @)string domain = email.Substring(atIndex + 1);Console.WriteLine($"Email: {email}");Console.WriteLine($"Username: {username}");Console.WriteLine($"Domain: {domain}");}}
The output of this code will be:
Email: [email protected]Username: userDomain: example.com
The above example demonstrates extracting the username from an email address and getting a portion of the domain.
Codebyte Example: Using C# .Substring() for File Path Processing
This example shows a real-world scenario where .Substring() is used to process file paths and extract file information:
This example processes a file path to extract different components.
Frequently Asked Questions
1. What happens if I pass a negative index to .Substring()?
The method will throw an ArgumentOutOfRangeException if the startIndex is negative or greater than the string length.
2. Can .Substring() modify the original string?
No, .Substring() returns a new string and does not modify the original string, as strings are immutable in C#.
3. What’s the difference between .Substring() and Span<char>?
.Substring() creates a new string object, while Span<char> provides a memory-efficient way to work with string segments without allocation.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours