.NET Framework 類別庫
String.Substring 方法 (Int32, Int32)

從這個執行個體擷取子字串。子字串起始於指定的字元位置,並且具有指定的長度。

命名空間: System
組件: mscorlib (在 mscorlib.dll 中)

語法

Visual Basic (宣告)
Public Function Substring ( _
    startIndex As Integer, _
    length As Integer _
) As String
Visual Basic (使用方式)
Dim instance As String
Dim startIndex As Integer
Dim length As Integer
Dim returnValue As String

returnValue = instance.Substring(startIndex, length)
C#
public string Substring (
    int startIndex,
    int length
)
C++
public:
String^ Substring (
    int startIndex, 
    int length
)
J#
public String Substring (
    int startIndex, 
    int length
)
JScript
public function Substring (
    startIndex : int, 
    length : int
) : String

參數

startIndex

子字串的起始索引。

length

子字串中的字元數。

傳回值

String,其相當於此執行個體中開始於 startIndex 且長度為 length 的子字串;如果 startIndex 等於此執行個體的長度,且 length 為零,則為 Empty
例外狀況

例外狀況類型條件

ArgumentOutOfRangeException

startIndex 加上 length 指示不在這個執行個體中的位置。

-或-

startIndexlength 小於零。

備註

startIndex 是以零起始的。

範例

下列程式碼範例會在三個案例下使用 Substring 方法,以隔離字串內的子字串。在兩個案例下,這些子字串會用於比較作業,而在第三個案例下,會因為指定了無效的參數而擲回例外狀況。

Visual Basic
Dim myString As String = "abc"
Dim test1 As Boolean = String.Compare(myString.Substring(2, 1), "c") = 0 ' This is true.
myString.Substring(3, 1) ' This throws ArgumentOutOfRangeException.
Dim test2 As Boolean = String.Compare(myString.Substring(3, 0), String.Empty) = 0 ' This is true.
C#
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.
C++
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.
J#
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;        
JScript
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

.NET Framework 並不支援各種平台的所有版本。如需支援平台版本的相關資訊,請參閱系統需求一節的內容。

版本資訊

.NET Framework

支援版本:2.0、1.1、1.0

.NET Compact Framework

支援版本:2.0、1.0
請參閱

標記 :


Page view tracker