C# Tutorial C# Advanced C# References

C# String - Substring() Method



The C# Substring() method is used to retrieve a substring from the given string. The substring starts at the specified index and continues to the end of the string or has a specified length.

Note: This method can be overloaded by passing different type of arguments to it.

Syntax

public string Substring (int startIndex);
public string Substring (int startIndex, int length);

Parameters

startIndex Specify the start index of the substring in the given string.
length Specify the length of the substring.

Return Value

Returns the substring from the given string.

Exception

Throws ArgumentOutOfRangeException, if the startIndex or length indicates a position which is not in the string.

Example:

In the example below, Substring() method is used to retrieve a substring from the given string called MyStr.

using System;

class MyProgram {
  static void Main(string[] args) {
    string MyStr = "Hello World";
 
    Console.WriteLine(MyStr.Substring(6));
    Console.WriteLine(MyStr.Substring(0,10));
  }
}

The output of the above code will be:

World
Hello Worl

❮ C# String Methods