Export (0) Print
Expand All

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
Not applicable.

Parameters

startIndex

The zero-based starting character position of a substring in this instance.

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 Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions

ADD
Show:
© 2014 Microsoft