String.Substring 方法

定義

從此實例中擷取一個子字串。

這位成員已經超載了。 欲了解此成員的完整資訊,包括語法、用法及範例,請點擊過載清單中的名稱。

多載

名稱 Description
Substring(Int32)

從此實例中擷取一個子字串。 子字串從指定的字元位置開始,並一直延伸到字串的末尾。

Substring(Int32, Int32)

從此實例中擷取一個子字串。 子字串從指定的字元位置開始,並具有指定的長度。

Substring(Int32)

來源:
String.Manipulation.cs
來源:
String.Manipulation.cs
來源:
String.Manipulation.cs
來源:
String.Manipulation.cs
來源:
String.Manipulation.cs

從此實例中擷取一個子字串。 子字串從指定的字元位置開始,並一直延伸到字串的末尾。

public:
 System::String ^ Substring(int startIndex);
public string Substring(int startIndex);
member this.Substring : int -> string
Public Function Substring (startIndex As Integer) As String

參數

startIndex
Int32

在此實例中子字串的從零開始字元位置。

傳回

一個字串等價於本實例中以 為 的 startIndex 子串,或 EmptystartIndex 等於本實例的長度。

例外狀況

startIndex 小於零或大於此實例的長度。

範例

以下範例示範如何從字串取得子字串。

string [] info = { "Name: Felica Walker", "Title: Mz.", 
                   "Age: 47", "Location: Paris", "Gender: F"};
int found = 0;

Console.WriteLine("The initial values in the array are:");
foreach (string s in info)
    Console.WriteLine(s);

Console.WriteLine("\nWe want to retrieve only the key information. That is:");        
foreach (string s in info) 
{
    found = s.IndexOf(": ");
    Console.WriteLine("   {0}", s.Substring(found + 2));
}

// The example displays the following output:
//       The initial values in the array are:
//       Name: Felica Walker
//       Title: Mz.
//       Age: 47
//       Location: Paris
//       Gender: F
//       
//       We want to retrieve only the key information. That is:
//          Felica Walker
//          Mz.
//          47
//          Paris
//          F
let info = 
    [| "Name: Felica Walker"; "Title: Mz."
       "Age: 47"; "Location: Paris"; "Gender: F" |]

printfn "The initial values in the array are:"
for s in info do
    printfn $"{s}"

printfn "\nWe want to retrieve only the key information. That is:"
for s in info do
    let found = s.IndexOf ": "
    printfn $"   {s.Substring(found + 2)}"

// The example displays the following output:
//       The initial values in the array are:
//       Name: Felica Walker
//       Title: Mz.
//       Age: 47
//       Location: Paris
//       Gender: F
//
//       We want to retrieve only the key information. That is:
//          Felica Walker
//          Mz.
//          47
//          Paris
//          F
Public Class SubStringTest
    Public Shared Sub Main()
        Dim info As String() = { "Name: Felica Walker", "Title: Mz.", 
                                 "Age: 47", "Location: Paris", "Gender: F"}
        Dim found As Integer = 0
       
        Console.WriteLine("The initial values in the array are:")
        For Each s As String In info
            Console.WriteLine(s)
        Next s

        Console.WriteLine(vbCrLf + "We want to retrieve only the key information. That is:")
        For Each s As String In info
            found = s.IndexOf(": ")
            Console.WriteLine("   {0}", s.Substring(found + 2))
        Next s
    End Sub 
End Class 
' The example displays the following output:
'       The initial values in the array are:
'       Name: Felica Walker
'       Title: Mz.
'       Age: 47
'       Location: Paris
'       Gender: F
'       
'       We want to retrieve only the key information. That is:
'          Felica Walker
'          Mz.
'          47
'          Paris
'          F

以下範例使用此 Substring 方法來分離由相等=()字元分隔的鍵值對。

String[] pairs = { "Color1=red", "Color2=green", "Color3=blue",
                 "Title=Code Repository" };
foreach (var pair in pairs) 
{
    int position = pair.IndexOf("=");
    if (position < 0)
        continue;
    Console.WriteLine("Key: {0}, Value: '{1}'", 
                   pair.Substring(0, position),
                   pair.Substring(position + 1));
}                          

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
let pairs = 
    [| "Color1=red"; "Color2=green"; "Color3=blue"
       "Title=Code Repository" |]
for pair in pairs do
    let position = pair.IndexOf "="
    if position >= 0 then
        printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'"

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
Module Example
   Public Sub Main()
      Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue",
                                "Title=Code Repository" }
      For Each pair In pairs
         Dim position As Integer = pair.IndexOf("=")
         If position < 0 then Continue For
         Console.WriteLine("Key: {0}, Value: '{1}'", 
                           pair.Substring(0, position),
                           pair.Substring(position + 1))
      Next                          
   End Sub
End Module
' The example displays the following output:
'     Key: Color1, Value: 'red'
'     Key: Color2, Value: 'green'
'     Key: Color3, Value: 'blue'
'     Key: Title, Value: 'Code Repository'

IndexOf 方法用於取得字串中等值字元的位置。 呼叫方法 Substring(Int32, Int32) 會擷取金鑰名稱,該名稱從字串的第一個字元開始,並延伸至呼叫回傳 IndexOf 的字元數。 呼叫該 Substring(Int32) 方法後,會擷取分配給鍵的值。 它從相等字元後方的一個字元位置開始,延伸到字串的末端。

備註

你呼叫 Substring(Int32) 方法,從一個從指定字元位置開始、到字串末尾的字串中提取子字串。 起始角色位置為零基礎;換句話說,字串的第一個字元位於索引 0,而非索引 1。 若要擷取從指定字元位置開始且在字串末尾前結束的子字串,呼叫該 Substring(Int32, Int32) 方法。

Note

此方法不會修改當前實例的值。 取而代之的是,它會回傳一個從當前字串位置開始 startIndex 的新字串。

要擷取以特定字元或字元序列開頭的子串,呼叫如 IndexOfIndexOf 的方法以取得 的 startIndex值。 第二個例子說明了這一點;它會擷取一個鍵值,該值從字元位置開始 =

startIndex 等於零,則該方法回傳原始字串不變。

另請參閱

適用於

Substring(Int32, Int32)

來源:
String.Manipulation.cs
來源:
String.Manipulation.cs
來源:
String.Manipulation.cs
來源:
String.Manipulation.cs
來源:
String.Manipulation.cs

從此實例中擷取一個子字串。 子字串從指定的字元位置開始,並具有指定的長度。

public:
 System::String ^ Substring(int startIndex, int length);
public string Substring(int startIndex, int length);
member this.Substring : int * int -> string
Public Function Substring (startIndex As Integer, length As Integer) As String

參數

startIndex
Int32

在此實例中子字串的從零開始字元位置。

length
Int32

子字串中的字元數。

傳回

一個字串等價於本實例中長度為 的lengthstartIndex子串,且起點為零,或EmptystartIndex 等於本實例的長度且length為零。

例外狀況

startIndex plus length 表示不屬於此例的局面。

-或-

startIndexlength 小於零。

範例

以下範例說明一個簡單的呼叫, Substring(Int32, Int32) 該方法從從第六個字元位置(即索引五)開始的字串中提取兩個字元。

String value = "This is a string.";
int startIndex = 5;
int length = 2;
String substring = value.Substring(startIndex, length);
Console.WriteLine(substring);

// The example displays the following output:
//       is
let value = "This is a string."
let startIndex = 5
let length = 2
let substring = value.Substring(startIndex, length)
printfn $"{substring}"

// The example displays the following output:
//       is
Module Example
   Public Sub Main()
      Dim value As String = "This is a string."
      Dim startIndex As Integer = 5
      Dim length As Integer = 2
      Dim substring As String = value.Substring(startIndex, length)
      Console.WriteLine(substring)
   End Sub
End Module
' The example displays the following output:
'       is

以下範例在以下三種情況下使用此 Substring(Int32, Int32) 方法來分離字串中的子字串。 在兩種情況下,子字串用於比較,第三種情況則因參數無效而拋出例外。

  • 它會擷取字串第三位(索引 2)的單一字元,並與「c」進行比較。 此比較結果 true為 。

  • 它從字串第四位置(索引 3)開始擷取零字元,並傳給該 IsNullOrEmpty 方法。 此回傳為真,因為呼叫 Substring 方法會回傳 String.Empty

  • 它嘗試從字串的第四個位置開始提取一個字元。 由於該位置沒有字元,方法呼叫會 ArgumentOutOfRangeException 拋出例外。

string myString = "abc";
bool test1 = myString.Substring(2, 1).Equals("c"); // This is true.
Console.WriteLine(test1);
bool test2 = string.IsNullOrEmpty(myString.Substring(3, 0)); // This is true.
Console.WriteLine(test2);
try
{
   string str3 = myString.Substring(3, 1); // This throws ArgumentOutOfRangeException.
   Console.WriteLine(str3);
}
catch (ArgumentOutOfRangeException e)
{
   Console.WriteLine(e.Message);
}

// The example displays the following output:
//       True
//       True
//       Index and length must refer to a location within the string.
//       Parameter name: length
let myString = "abc"
let test1 = myString.Substring(2, 1).Equals "c" // This is true.
printfn $"{test1}"
let test2 = String.IsNullOrEmpty(myString.Substring(3, 0)) // This is true.
printfn $"{test2}"
try
    let str3 = myString.Substring(3, 1) // This throws ArgumentOutOfRangeException.
    printfn $"{str3}"
with :? ArgumentOutOfRangeException as e ->
    printfn $"{e.Message}"

// The example displays the following output:
//       True
//       True
//       Index and length must refer to a location within the string.
//       Parameter name: length
Public Class Sample
   Public Shared Sub Main()
      Dim myString As String = "abc"
      Dim test1 As Boolean = myString.Substring(2, 1).Equals("c") ' This is true.
      Console.WriteLine(test1)
      Dim test2 As Boolean = String.IsNullOrEmpty(myString.Substring(3, 0)) ' This is true.
      Console.WriteLine(test2)
      Try  
         Dim str3 As String = myString.Substring(3, 1) ' This throws ArgumentOutOfRangeException.
         Console.WriteLine(str3)
      Catch e As ArgumentOutOfRangeException
         Console.WriteLIne(e.Message)
      End Try   
   End Sub
End Class 
' The example displays the following output:
'       True
'       True
'       Index and length must refer to a location within the string.
'       Parameter name: length

以下範例使用此 Substring 方法來分離由相等=()字元分隔的鍵值對。

String[] pairs = { "Color1=red", "Color2=green", "Color3=blue",
                 "Title=Code Repository" };
foreach (var pair in pairs) 
{
    int position = pair.IndexOf("=");
    if (position < 0)
        continue;
    Console.WriteLine("Key: {0}, Value: '{1}'", 
                   pair.Substring(0, position),
                   pair.Substring(position + 1));
}                          

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
let pairs = 
    [| "Color1=red"; "Color2=green"; "Color3=blue"
       "Title=Code Repository" |]
for pair in pairs do
    let position = pair.IndexOf "="
    if position >= 0 then
        printfn $"Key: {pair.Substring(0, position)}, Value: '{pair.Substring(position + 1)}'"

// The example displays the following output:
//     Key: Color1, Value: 'red'
//     Key: Color2, Value: 'green'
//     Key: Color3, Value: 'blue'
//     Key: Title, Value: 'Code Repository'
Module Example
   Public Sub Main()
      Dim pairs() As String = { "Color1=red", "Color2=green", "Color3=blue",
                                "Title=Code Repository" }
      For Each pair In pairs
         Dim position As Integer = pair.IndexOf("=")
         If position < 0 then Continue For
         Console.WriteLine("Key: {0}, Value: '{1}'", 
                           pair.Substring(0, position),
                           pair.Substring(position + 1))
      Next                          
   End Sub
End Module
' The example displays the following output:
'     Key: Color1, Value: 'red'
'     Key: Color2, Value: 'green'
'     Key: Color3, Value: 'blue'
'     Key: Title, Value: 'Code Repository'

IndexOf 方法用於取得字串中等值字元的位置。 呼叫方法 Substring(Int32, Int32) 會擷取金鑰名稱,該名稱從字串的第一個字元開始,並延伸至呼叫回傳 IndexOf 的字元數。 呼叫該 Substring(Int32) 方法後,會擷取分配給鍵的值。 它從相等字元後方的一個字元位置開始,延伸到字串的末端。

備註

你呼叫 Substring(Int32, Int32) 方法從一個字串開始、在字串結尾之前結束的字串中提取子字串。 起始角色位置為零基礎;換句話說,字串的第一個字元位於索引 0,而非索引 1。 若要擷取從指定字元位置開始並持續到字串末尾的子串,呼叫該 Substring(Int32) 方法。

Note

此方法不會修改當前實例的值。 取而代之的是,它會回傳一個新的字串,字 length 元從 startIndex 當前字串的位置開始。

參數 length 代表從目前字串實例中要提取的總字元數。 這包括在索引 startIndex中找到的起始字元。 換句話說,該 Substring 方法嘗試從索引 startIndex 到索引 startIndex + length - 1 中提取字元。

要擷取以特定字元或字元序列開頭的子串,呼叫如 IndexOfLastIndexOf 的方法以取得 的 startIndex值。

如果子字串應該從 startIndex 延伸到指定的字元序列,你可以呼叫像 IndexOf or LastIndexOf 這類方法來取得結尾字元或字元序列的索引。 接著你可以將該值轉換為字串中的索引位置,方法如下:

  • 如果你搜尋一個字元標記子串的結尾,參數lengthendIndex - startIndex於 + 1,其中 endIndex 是 or IndexOf 方法的LastIndexOf回傳值。 以下範例從字串中擷取連續的「b」字元區塊。

    String s = "aaaaabbbcccccccdd";
    Char charRange = 'b';
    int startIndex = s.IndexOf(charRange);
    int endIndex = s.LastIndexOf(charRange);
    int length = endIndex - startIndex + 1;
    Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
                    s, startIndex, length, 
                    s.Substring(startIndex, length));
    
    // The example displays the following output:
    //       aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
    let s = "aaaaabbbcccccccdd"
    let charRange = 'b'
    let startIndex = s.IndexOf charRange
    let endIndex = s.LastIndexOf charRange
    let length = endIndex - startIndex + 1
    printfn $"{s}.Substring({startIndex}, {length}) = {s.Substring(startIndex, length)}"
    
    // The example displays the following output:
    //       aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
    Module Example
       Public Sub Main()
          Dim s As String = "aaaaabbbcccccccdd"
          Dim charRange As Char = "b"c
          Dim startIndex As Integer = s.Indexof(charRange)
          Dim endIndex As Integer = s.LastIndexOf(charRange)
          Dim length = endIndex - startIndex + 1
          Console.WriteLine("{0}.Substring({1}, {2}) = {3}",
                            s, startIndex, length, 
                            s.Substring(startIndex, length))
       End Sub
    End Module
    ' The example displays the following output:
    '     aaaaabbbcccccccdd.Substring(5, 3) = bbb
    
  • 如果你搜尋了多個要標記子字串結尾的字元,length參數等endIndex + endMatchLength - startIndex於 ,其中 endIndex 是 or IndexOf 方法的LastIndexOf回傳值,是endMatchLength標記子串結束的字元序列長度。 以下範例擷取包含 XML <definition> 元素的文字區塊。

    String s = "<term>extant<definition>still in existence</definition></term>";
    String searchString = "<definition>";
    int startIndex = s.IndexOf(searchString);
    searchString = "</" + searchString.Substring(1);
    int endIndex = s.IndexOf(searchString);
    String substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex);
    Console.WriteLine("Original string: {0}", s);
    Console.WriteLine("Substring;       {0}", substring); 
    
    // The example displays the following output:
    //     Original string: <term>extant<definition>still in existence</definition></term>
    //     Substring;       <definition>still in existence</definition>
    
    let s = "<term>extant<definition>still in existence</definition></term>"
    let searchString = "<definition>"
    let startIndex = s.IndexOf(searchString)
    let searchString = "</" + searchString.Substring 1
    let endIndex = s.IndexOf searchString
    let substring = s.Substring(startIndex, endIndex + searchString.Length - startIndex)
    printfn $"Original string: {s}"
    printfn $"Substring;       {substring}"
    
    // The example displays the following output:
    //     Original string: <term>extant<definition>still in existence</definition></term>
    //     Substring;       <definition>still in existence</definition>
    
    Module Example
       Public Sub Main()
          Dim s As String = "<term>extant<definition>still in existence</definition></term>"
          Dim searchString As String = "<definition>"
          Dim startindex As Integer = s.IndexOf(searchString)
          searchString = "</" + searchString.Substring(1)
          Dim endIndex As Integer = s.IndexOf(searchString)
          Dim substring As String = s.Substring(startIndex, endIndex + searchString.Length - StartIndex)
          Console.WriteLine("Original string: {0}", s)
          Console.WriteLine("Substring;       {0}", substring) 
       End Sub
    End Module
    ' The example displays the following output:
    '   Original string: <term>extant<definition>still in existence</definition></term>
    '   Substring;       <definition>still in existence</definition>
    
  • 若字元或字元序列未包含在子字串結尾,length參數等於 endIndex - startIndex,其中 endIndex 是 或IndexOf方法的LastIndexOf回傳值。

startIndex 等於零且 length 等於當前字串長度,則該方法會回傳原始字串不變。

另請參閱

適用於