Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

String.Substring Method (Int32, Int32)

Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

public string Substring (
	int startIndex,
	int length
)
public String Substring (
	int startIndex, 
	int length
)
public function Substring (
	startIndex : int, 
	length : int
) : String

Parameters

startIndex

The index of the start of the substring.

length

The number of characters in the substring.

Return Value

A String equivalent to the substring of length length that begins at startIndex in this instance, or Empty if startIndex is equal to the length of this instance and length is zero.

Exception typeCondition

ArgumentOutOfRangeException

startIndex plus length indicates a position not within this instance.

-or-

startIndex or length is less than zero.

startIndex is zero-based.

The following code example uses the Substring method in three cases to isolate substrings within a string. In two cases the substrings are used in comparisons, and in the third case an exception is thrown because invalid parameters are specified.

String myString = "abc";
bool test1 = String.Compare(myString.Substring(2, 1), "c") == 0; // This is true.
myString.Substring(3, 1); // This throws ArgumentOutOfRangeException.
bool test2 = String.Compare(myString.Substring(3, 0), String.Empty) == 0; // This is true.

String myString = "abc";
// This is true.
boolean test1 = String.Compare(myString.Substring(2, 1), "c") == 0;        
myString.Substring(3, 1); // This throws ArgumentOutOfRangeException.
// This is true.
boolean test2 = String.Compare(myString.Substring(3, 0), " ") == 0;        

var myString : String = "abc";
var test1 : boolean = String.Compare(myString.Substring(2, 1), "c") == 0; // This is true.
myString.Substring(3, 1);  // This throws ArgumentOutOfRangeException.
var test2 : boolean = String.Compare(myString.Substring(3, 0), String.Empty) == 0; // This is true.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

Show:
© 2014 Microsoft