The Substring()
method returns a substring from the given string.
Example
using System;
namespace CsharpString
{
class Test
{
public static void Main(string[] args)
{
string text = "C# is fun";
// Returns substring of length 3 from index 6
Console.WriteLine(text.Substring(6, 3));
Console.ReadLine();
}
}
}
// Output: fun
Substring() Syntax
The syntax of the string Substring()
method is:
Substring(int startIndex, int length)
Here, Substring()
is a method of class String
.
Substring() Parameters
The Substring()
method takes the following parameters:
- startIndex - the beginning index of the substring
- length - (optional) - length of the substring
Substring() Return Value
The Substring()
method returns a substring from the given string.
Example 1: C# Substring() Without Length
using System;
namespace CsharpString
{
class Test
{
public static void Main(string[] args)
{
string text = "Programiz";
// Returns substring from the second character
string result = text.Substring(1);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Output
rogramiz
Notice this line in the above example:
string result = text.Substring(1);
The code text.Substring(1)
returns the substring from the second character of "Programiz"
.
Example 2: C# Substring() With Length
using System;
namespace CsharpString
{
class Test
{
public static void Main(string[] args)
{
string text = "Programiz is for programmers";
// Returns substring of length 9 from the first character
string result = text.Substring(0, 9);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Output
Programiz
Notice this line in the above example:
string result = text.Substring(0, 9);
Here,
- 0 (the first character of text) is the beginning index of the substring
- 9 is the length of the substring
This gives us the substring "Programiz"
.
Example 3: C# Substring() Before Specific Character
using System;
namespace CsharpString
{
class Test
{
public static void Main(string[] args)
{
string text = "C#. Programiz";
// Returns substring from index 0 to index before '.'
string result = text.Substring(0, text.IndexOf('.'));
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Output
C#
Here, text.IndexOf('.')
gives the length of the substring, which is the index of '.'
.