C# Tutorial C# Advanced C# Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C# - String Substring() Method



The C# string 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

5