A substring in C# is a contiguous sequence of characters within a string. Basically, a substring is a portion of a string. This article and code examples demonstrate how to retrieve a substring from a string using C# and .NET Core.
C# String.Substring method
In C# and .NET, a string is represented by the String class. The String.Substring method retrieves a substring from a string instance in C#. The method has the following two overloaded forms.
Substring(Int32) - Retrieves a substring from the specified position to the end of the string.Substring(Int32, Int32 - Retrieves a substring from this instance from the specified position for the specified length.
Get first n characters substring from a string in C#
String characters are zero-indexed. Means, the position of the first characters in a string starts at 0th position.
Let’s say, you want to get a substring of first 12 characters from a string. We can use the Substring method and pass it starting index 0 and length of the substring 12 to get first 12 char substring from a string.
// C# program to demonstrate the
// String.Substring Method (startIndex)
using System;
class CodersArts{
// Main Method
public static void Main()
{
// define string
String str = "SusheelKumarVishwakarma";
Console.WriteLine("String : " + str);
// retrieve the substring from index 5
Console.WriteLine("Sub String1: " + str.Substring(5));
// retrieve the substring from index 8
Console.WriteLine("Sub String2: " + str.Substring(8));
}
}
Output:
String : SusheelKumarVishwakarma
Sub String1: elKumarVishwakarma
Sub String2: Sushe