|
1 | 1 | --- |
2 | 2 | Title: '.Substring()' |
3 | | -Description: 'Returns the substring of a string instance starting at a given index.' |
| 3 | +Description: 'Extracts a portion of a string starting from a specified index position.' |
4 | 4 | Subjects: |
5 | | - - 'Code Foundations' |
6 | 5 | - 'Computer Science' |
| 6 | + - 'Web Development' |
7 | 7 | Tags: |
| 8 | + - 'Data Types' |
8 | 9 | - 'Methods' |
9 | 10 | - 'Strings' |
10 | 11 | CatalogContent: |
11 | 12 | - 'learn-c-sharp' |
12 | 13 | - 'paths/computer-science' |
13 | 14 | --- |
14 | 15 |
|
15 | | -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`. |
| 16 | +The C# **`.Substring()`** method is a built-in [string](https://www.codecademy.com/resources/docs/c-sharp/strings) 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. |
16 | 17 |
|
17 | | -## Syntax |
| 18 | +## Syntax of C# `.Substring()` |
18 | 19 |
|
19 | 20 | ```pseudo |
20 | | -.Substring(int startIndex) |
| 21 | +public string Substring(int startIndex) |
| 22 | +public string Substring(int startIndex, int length) |
21 | 23 | ``` |
22 | 24 |
|
23 | | -Or, alternatively: |
| 25 | +**Parameters:** |
24 | 26 |
|
25 | | -```pseudo |
26 | | -.Substring(int startIndex, int length) |
27 | | -``` |
| 27 | +- `startIndex`: The zero-based starting position from where the substring begins. The type is `System.Int32`. |
| 28 | +- `length` (optional): The number of characters to include in the substring. The type is `System.Int32`. |
| 29 | + |
| 30 | +**Return value:** |
| 31 | + |
| 32 | +Both methods return a new string (`System.String`) containing the extracted substring. |
28 | 33 |
|
29 | | -- `startIndex`: The index from where the substring starts. |
30 | | -- `Length` (Optional): The number of characters to include in the substring.. |
| 34 | +**Exceptions:** |
31 | 35 |
|
32 | | -## Example |
| 36 | +The method throws `ArgumentOutOfRangeException` if: |
33 | 37 |
|
34 | | -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: |
| 38 | +- `startIndex` is less than zero or greater than the length of the string |
| 39 | +- `length` is less than zero |
| 40 | +- `startIndex` plus `length` indicates a position not within the current string |
| 41 | + |
| 42 | +## Example 1: Basic Usage of `.Substring()` |
| 43 | + |
| 44 | +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: |
35 | 45 |
|
36 | 46 | ```cs |
37 | 47 | using System; |
38 | 48 |
|
39 | 49 | public class Program |
40 | 50 | { |
41 | | - public static void Main() |
42 | | - { |
43 | | - string str = "Codecademy"; |
44 | | - Console.WriteLine(str.Substring(4)); |
45 | | - } |
| 51 | + public static void Main() |
| 52 | + { |
| 53 | + string text = "Hello World"; |
| 54 | + |
| 55 | + // Extract substring from index 6 to the end |
| 56 | + string result = text.Substring(6); |
| 57 | + |
| 58 | + Console.WriteLine($"Original: {text}"); |
| 59 | + Console.WriteLine($"Substring from index 6: {result}"); |
| 60 | + } |
46 | 61 | } |
47 | 62 | ``` |
48 | 63 |
|
49 | | -The above example results in the following output: |
| 64 | +The output of this example will be: |
50 | 65 |
|
51 | 66 | ```shell |
52 | | -cademy |
| 67 | +Original: Hello World |
| 68 | +Substring from index 6: World |
53 | 69 | ``` |
54 | 70 |
|
55 | | -## Example 2 |
| 71 | +This example extracts all characters starting from index 6 (the letter 'W') to the end of the string. |
| 72 | + |
| 73 | +## Example 2: Extract Characters with Length Using `.Substring()` |
56 | 74 |
|
57 | | -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"`. |
| 75 | +This example shows how to use the `.Substring()` method with both parameters to extract a specific number of characters: |
58 | 76 |
|
59 | 77 | ```cs |
60 | 78 | using System; |
61 | 79 |
|
62 | 80 | public class Program |
63 | 81 | { |
64 | | - public static void Main() |
65 | | - { |
66 | | - string str = "Codecademy"; |
67 | | - Console.WriteLine(str.Substring(2, 6)); |
68 | | - } |
| 82 | + public static void Main() |
| 83 | + { |
| 84 | + string email = "user@example.com"; |
| 85 | + |
| 86 | + // Extract username (characters before @) |
| 87 | + int atIndex = email.IndexOf('@'); |
| 88 | + string username = email.Substring(0, atIndex); |
| 89 | + |
| 90 | + // Extract domain (characters after @) |
| 91 | + string domain = email.Substring(atIndex + 1); |
| 92 | + |
| 93 | + Console.WriteLine($"Email: {email}"); |
| 94 | + Console.WriteLine($"Username: {username}"); |
| 95 | + Console.WriteLine($"Domain: {domain}"); |
| 96 | + } |
69 | 97 | } |
70 | 98 | ``` |
71 | 99 |
|
72 | | -The above code generates the following output: |
| 100 | +The output of this code will be: |
73 | 101 |
|
74 | | -````shell |
75 | | -decade |
| 102 | +```shell |
| 103 | +Email: user@example.com |
| 104 | +Username: user |
| 105 | +Domain: example.com |
| 106 | +``` |
| 107 | + |
| 108 | +The above example demonstrates extracting the username from an email address and getting a portion of the domain. |
76 | 109 |
|
77 | | -## Codebyte Example |
| 110 | +## Codebyte Example: Using C# `.Substring()` for File Path Processing |
78 | 111 |
|
79 | | -The below code demonstrates how to use the Substring method: |
| 112 | +This example shows a real-world scenario where `.Substring()` is used to process file paths and extract file information: |
80 | 113 |
|
81 | 114 | ```codebyte/csharp |
82 | 115 | using System; |
83 | 116 |
|
84 | | -public class Example |
| 117 | +public class Program |
85 | 118 | { |
86 | | - public static void Main(string[] args) |
87 | | - { |
88 | | - string Name1 = "Brad"; |
89 | | - string Name2 = "Angelina"; |
90 | | -
|
91 | | - Console.WriteLine(Name1.Substring(1)); |
92 | | - Console.WriteLine(Name2.Substring(1)); |
93 | | - } |
| 119 | + public static void Main() |
| 120 | + { |
| 121 | + string filePath = "C:\\Documents\\Projects\\MyApplication.exe"; |
| 122 | +
|
| 123 | + // Extract filename with extension |
| 124 | + int lastSlash = filePath.LastIndexOf('\\'); |
| 125 | + string fileName = filePath.Substring(lastSlash + 1); |
| 126 | +
|
| 127 | + // Extract file extension |
| 128 | + int dotIndex = fileName.LastIndexOf('.'); |
| 129 | + string extension = fileName.Substring(dotIndex + 1); |
| 130 | +
|
| 131 | + // Extract filename without extension |
| 132 | + string nameOnly = fileName.Substring(0, dotIndex); |
| 133 | +
|
| 134 | + Console.WriteLine($"Full path: {filePath}"); |
| 135 | + Console.WriteLine($"Filename: {fileName}"); |
| 136 | + Console.WriteLine($"Extension: {extension}"); |
| 137 | + Console.WriteLine($"Name only: {nameOnly}"); |
| 138 | + } |
94 | 139 | } |
95 | | -```` |
| 140 | +``` |
| 141 | + |
| 142 | +This example processes a file path to extract different components. |
| 143 | + |
| 144 | +## Frequently Asked Questions |
| 145 | + |
| 146 | +### 1. What happens if I pass a negative index to `.Substring()`? |
| 147 | + |
| 148 | +The method will throw an `ArgumentOutOfRangeException` if the `startIndex` is negative or greater than the string length. |
| 149 | + |
| 150 | +### 2. Can `.Substring()` modify the original string? |
| 151 | + |
| 152 | +No, `.Substring()` returns a new string and does not modify the original string, as strings are immutable in C#. |
| 153 | + |
| 154 | +### 3. What's the difference between `.Substring()` and `Span<char>`? |
| 155 | + |
| 156 | +`.Substring()` creates a new string object, while `Span<char>` provides a memory-efficient way to work with string segments without allocation. |
0 commit comments