C# String - Substring() Method



The C# String Substring() method is used to retrieve a substring from the current instance of a string, starting at a specified character position and continuing to the end of the string. If a specific length is given, the method returns the substring starting from the character position and extending to the given length.

Syntax

Following are the syntax of the C# string Substring() method −

Syntax with only startIndex −

 public string Substring (int startIndex); 

Syntax with both startIndex and length −

 public string Substring(int startIndex, int length); 

Parameters

This method accepts the following parameters −

  • startIndex: It represents the starting character position of the substring in the current string's instance.
  • length: It represents the number of characters to include in the substring.

Return Value

This method returns a new string which is a substring of the current string's instance, starting at the specified position and having the specified length.

Example 1: Extract a Substring From String

Here is a basic example of the Substring() method, where we extract a substring that starts with a specified index position and continues at the end of the current instance −

 using System; class Program { public static void Main() { string text = "Hello, tpians!"; string Substring = text.Substring(3); Console.Write("This is substring: "+ Substring); } } 

Output

Following is the output −

 This is substring: lo, tpians! 

Example 2: Extract Substring within Specified Length

Let's look at another example. Here, we use the substring() method to retrieve a substring from a given starting position to a specified length. −

 using System; class Program { public static void Main() { string text = "Hello, tpians!"; string Substring = text.Substring(3, 7); Console.Write("This is substring: "+ Substring); } } 

Output

Following is the output −

 This is substring: lo, tpi 

Example 3: Extract First N Characters

In this example, we use the Substring() method to extract the first n character. To extract the first n character, we need to mention startIndex at '0' and then the length −

 using System; class Program { public static void Main() { string text = "Hello, tutorialspoint"; string Substring = text.Substring(0, 10); Console.Write("First n character: "+ Substring); } } 

Output

Following is the output −

 True 

Example 4: Handle Out-of-Range Scenario

The below example handles the out-of-range scenario. If the start index is greater than the length of the string or '-1', then we get the error −

 using System; class Program { public static void Main() { string str = "Hi, tutorialspoint"; try { string substring = str.Substring(20); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"Error: {ex.Message}"); } } } 

Output

Following is the output −

 Error: startIndex cannot be larger than length of string. Parameter name: startIndex 
csharp_strings.htm
Advertisements