diff --git a/content/c-sharp/concepts/strings/terms/substring/substring.md b/content/c-sharp/concepts/strings/terms/substring/substring.md index 2e41afca218..5437c341740 100644 --- a/content/c-sharp/concepts/strings/terms/substring/substring.md +++ b/content/c-sharp/concepts/strings/terms/substring/substring.md @@ -1,10 +1,11 @@ --- Title: '.Substring()' -Description: 'Returns the substring of a string instance starting at a given index.' +Description: 'Extracts a portion of a string starting from a specified index position.' Subjects: - - 'Code Foundations' - 'Computer Science' + - 'Web Development' Tags: + - 'Data Types' - 'Methods' - 'Strings' CatalogContent: @@ -12,84 +13,145 @@ CatalogContent: - 'paths/computer-science' --- -The **`.Substring()`** method is a string method that returns a substring of a string starting at the specified index. It will return all characters from that index to the end unless a maximum length is specified. If the starting index equals the string length, it returns an empty string (`""`). If the index is greater than the string length, it throws an `ArgumentOutOfRangeException`. +The **`.Substring()`** method is a built-in [string](https://www.codecademy.com/resources/docs/c-sharp/strings) method in C# 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. + +The `.Substring()` method is commonly used in text processing, data parsing, string manipulation, and when working with user input validation. It is essential for extracting specific portions of strings such as parsing file extensions, extracting usernames from email addresses, or getting substrings from formatted data like dates or identification numbers. ## Syntax ```pseudo -.Substring(int startIndex) +public string Substring(int startIndex, int length) ``` -Or, alternatively: +**Parameters:** -```pseudo -.Substring(int startIndex, int length) -``` +- `startIndex`: The zero-based starting position from where the substring begins. The type is `System.Int32`. +- `length` (optional): The number of characters to include in the substring. The type is `System.Int32`. + +**Return value:** + +Both methods return a new string (`System.String`) containing the extracted substring. + +**Exceptions:** + +The method throws `ArgumentOutOfRangeException` if: -- `startIndex`: The index from where the substring starts. -- `Length` (Optional): The number of characters to include in the substring.. +- `startIndex` is less than zero or greater than the length of the string +- `length` is less than zero +- `startIndex` plus `length` indicates a position not within the current string -## Example +## Example 1: Basic Usage of `.Substring()` -In this example, `.Substring()` is used to return the substring of "Codecademy" starting at index `4` and includes all characters from that position to the end of the string: +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: ```cs using System; public class Program { - public static void Main() - { - string str = "Codecademy"; - Console.WriteLine(str.Substring(4)); - } + public static void Main() + { + string text = "Hello World"; + + // Extract substring from index 6 to the end + string result = text.Substring(6); + + Console.WriteLine($"Original: {text}"); + Console.WriteLine($"Substring from index 6: {result}"); + } } ``` -The above example results in the following output: +The output of this example will be: ```shell -cademy +Original: Hello World +Substring from index 6: World ``` -## Example 2 +This example extracts all characters starting from index 6 (the letter 'W') to the end of the string. + +## Example 2: Extract Characters with Length -In this example, `.Substring()` is used with the optional `length` parameter to return a substring of 6 characters starting from index `2` of the string `"Codecademy"`. +This example shows how to use the `.Substring()` method with both parameters to extract a specific number of characters: ```cs using System; public class Program { - public static void Main() - { - string str = "Codecademy"; - Console.WriteLine(str.Substring(2, 6)); - } + public static void Main() + { + string email = "user@example.com"; + + // Extract username (characters before @) + int atIndex = email.IndexOf('@'); + string username = email.Substring(0, atIndex); + + // Extract domain extension + string domain = email.Substring(atIndex + 1, 7); + + Console.WriteLine($"Email: {email}"); + Console.WriteLine($"Username: {username}"); + Console.WriteLine($"Domain: {domain}"); + } } ``` -The above code generates the following output: +The output of this code will be: -````shell -decade +```shell +Email: user@example.com +Username: user +Domain: example +``` -## Codebyte Example +This example demonstrates extracting the username from an email address and getting a portion of the domain. -The below code demonstrates how to use the Substring method: +## Codebyte Example: File Path Processing + +This example shows a real-world scenario where `.Substring()` is used to process file paths and extract file information: ```codebyte/csharp using System; -public class Example +public class Program { - public static void Main(string[] args) - { - string Name1 = "Brad"; - string Name2 = "Angelina"; - - Console.WriteLine(Name1.Substring(1)); - Console.WriteLine(Name2.Substring(1)); - } + public static void Main() + { + string filePath = "C:\\Documents\\Projects\\MyApplication.exe"; + + // Extract filename with extension + int lastSlash = filePath.LastIndexOf('\\'); + string fileName = filePath.Substring(lastSlash + 1); + + // Extract file extension + int dotIndex = fileName.LastIndexOf('.'); + string extension = fileName.Substring(dotIndex + 1); + + // Extract filename without extension + string nameOnly = fileName.Substring(0, dotIndex); + + Console.WriteLine($"Full path: {filePath}"); + Console.WriteLine($"Filename: {fileName}"); + Console.WriteLine($"Extension: {extension}"); + Console.WriteLine($"Name only: {nameOnly}"); + } } -```` +``` + +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`? + +`.Substring()` creates a new string object, while `Span` provides a memory-efficient way to work with string segments without allocation.