C# Substring

Substring method example

Substring extracts strings. It requires that you indicate a start index and a length. It then returns a completely new string with the characters in that range. We use two overloaded Substring methods.

Overload

Note:Substring(0, 3) returns a substring containing the first three chars.
Substring(3, 3) returns the second three chars.

Also:Substring(6) returns a substring containing all chars after the first six.

First part

First

Initially here you have a string and you want to extract the first part into a new string. We can use the Substring instance method with two parameters here, the first being 0 and the second being the desired length.

String Length
Program that uses Substring: C#

using System;

class Program
{
    static void Main()
    {
	string input = "OneTwoThree";

	// Get first three characters
	string sub = input.Substring(0, 3);
	Console.WriteLine("Substring: {0}", sub);
    }
}

Output

Substring: One
Note

The Substring method is an instance method on the string class, which means you must have a non-null string to use it without triggering an exception. This program will extract the first three characters into a new string reference.

And:The string is separately allocated on the managed heap. A new string is created by Substring.

One parameter

Continuing on, we see the Substring overloaded method that takes one parameter, the start index int. The second parameter is considered the largest possible, meaning the substring ends at the last char.

Program that calls Substring, one argument: C#

using System;

class Program
{
    static void Main()
    {
	string input = "OneTwoThree";
	// Indexes:
	// 0:'O'
	// 1:'n'
	// 2:'e'
	// 3:'T'
	// 4:'w' ...

	string sub = input.Substring(3);
	Console.WriteLine("Substring: {0}", sub);
    }
}

Output

Substring: TwoThree
Program icon

The program describes logic that takes all the characters in the input string excluding the first three. The end result is that you extract the last several characters. The length is reduced by three.

Middle chars

Here we take several characters in the middle of a string and place them into a new string. To take a middle substring, pass two arguments to Substring. You will want each parameter to be a non-zero value to avoid the edge characters.

In this example, the two parameters say, "I want the substring at index 3 with a length of three." These are the third through sixth characters. The program then displays the resulting string data.

Program that uses Substring, two arguments: C#

using System;

class Program
{
    static void Main()
    {
	string input = "OneTwoThree";

	string sub = input.Substring(3, 3);
	Console.WriteLine("Substring: {0}", sub);
    }
}

Output

Substring: Two

Slice

Programming tip

We note that you can add an extension method to "slice" strings as is possible in languages such as JavaScript. The Substring method in C# doesn't use the same semantics as the Slice method from JavaScript and Python.

However:You can develop an extension method that efficiently fills this need. An example implementation is available.

String Slice

Avoid chars

We can avoid copying the last several characters of a string. This example eliminates the last five characters from the input string. The Substring call returns a new string without them.

Program that uses Substring, ending characters: C#

using System;

class Program
{
    static void Main()
    {
	string input = "OneTwoThree";

	string sub = input.Substring(0, input.Length - 5);
	Console.WriteLine("Substring: {0}", sub);
    }
}

Output

Substring: OneTwo

Research

I found some reference material on the MSDN website provided by Microsoft. The Substring articles on MSDN are not helpful. They do not say anything that you cannot find from Visual Studio's IntelliSense.

String.Substring Method: MSDN

Exceptions

Warning: exclamation mark

There are some exceptions that can be raised when the Substring instance method on the string type is called with incorrect arguments. This example triggers the ArgumentOutOfRangeException.

Tip:When you try to go beyond the string length, or use an argument < 0, you get an ArgumentOutOfRangeException.

ArgumentException
Program that shows Substring exceptions: C#

using System;

class Program
{
    static void Main()
    {
	string input = "OneTwoThree";

	try
	{
	    string sub = input.Substring(-1);
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex);
	}

	try
	{
	    string sub = input.Substring(0, 100);
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex);
	}
    }
}

Output

System.ArgumentOutOfRangeException
System.String.InternalSubStringWithChecks

System.ArgumentOutOfRangeException
System.String.InternalSubStringWithChecks

Benchmark

Performance optimization

Performance is important. String-related allocations can require a lot of time in some programs. We wanted to see if taking characters and putting them into a char array could be faster than calling Substring.

So:The result was that Substring is faster. But if you want to extract only certain characters, consider the char[] approach shown.

Char Array
Data tested

string s = "onetwothree"; // Input

Char array method version

char[] c = new char[3];
c[0] = s[3];
c[1] = s[4];
c[2] = s[5];
string x = new string(c); // "two"
if (x == null)
{
}

Substring version

string x = s.Substring(3, 3); // "two"
if (x == null)
{
}

Substring benchmark result
    Substring was faster.

New char[] array: 2382 ms
Substring:        2053 ms [faster]

The above code is simply a benchmark you can run in Visual Studio to see the performance difference of Substring and char[] arrays. It is best to use Substring when it has equivalent behavior.

Benchmark Programs

One character

It is possible to take a one-character substring. But if you simply use the string indexer to get a character, such as with value[5], you will have better performance. And sometimes the improvement is significant.

Why is it faster? Substring must create a whole object on the managed heap. The string indexer just returns a char, which is a value type like an integer. So we replace an allocated object with a small value type.

StringsChar

Summary

C# programming language

We saw many examples concentrated on the Substring instance method with one or two arguments. With MSDN, we researched the Substring method.
Finally we learned about Slice,
Substring exceptions,
and Substring performance.

Review:Substring is useful.
It can help simplify your programs.
It has no significant performance problems.


C#: String