Summary: in this tutorial, you will learn how to use the C# String Substring() method to extract a portion of a string.
Introduction to the C# String Substring() method
The String Substring() method allows you to extract a portion of a string. It returns a new string that contains a specified number of characters from the original string, starting at a specified index.
Here’s the syntax of the Substring() method:
public string Substring(
int startIndex
);Code language: C# (cs)In this syntax, the startIndex specifies the zero-based starting character position of a substring in the string. The method returns a substring that starts at the startIndex and continues to the end of the string.
The following example uses the Substring() method to extract the AM/PM from a time string:
using static System.Console;
var time = "12:30 PM";
var startIndex = time.IndexOf(' ');
var result = time.Substring(startIndex + 1);
WriteLine(result);Code language: C# (cs)Output:
PMCode language: C# (cs)How it works.
First, find the index of the space in the time string using the IndexOf() method.
Second, extract a substring that starts from the index + 1 to the end of the string using the Substring() method.
The Substring() method has an overload that allows you to specify the length of the substring to return:
public string Substring (
int startIndex,
int length
);Code language: C# (cs)In this syntax, the length specifies the number of characters included in the substring.
For example, the following program uses the Substring() method to extract the minute part of a time string:
using static System.Console;
var time = "12:30 PM";
var startIndex = time.IndexOf(':');
var result = time.Substring(startIndex + 1, 2);
WriteLine(result); // 30Code language: C# (cs)Output:
30Code language: C# (cs)How it works.
First, find the position of the character in the time string using IndexOf() method:
var startIndex = time.IndexOf(':');Code language: C# (cs)Second, extract the minutes starting from the position after the character : and limit the number of characters in the substring to 2:
var result = time.Substring(startIndex + 1, 2);Code language: C# (cs)Summary
- Use the C# String
Substring()method to return a new string that contains a specified number of characters from the original string, starting at a specified index.