String.Substring Metoda

Definicja

Pobiera podciąg z tego wystąpienia.

Ten element członkowski jest przeciążony. Aby uzyskać pełne informacje dotyczące tego elementu członkowskiego, w tym informacje o jego składni i zastosowaniu oraz odpowiednie przykłady, kliknij nazwę na liście przeciążeń.

Przeciążenia

Substring(Int32)

Pobiera podciąg z tego wystąpienia. Podciąg zaczyna się od określonego położenia znaku i kontynuuje koniec ciągu.

Substring(Int32, Int32)

Pobiera podciąg z tego wystąpienia. Podciąg zaczyna się od określonej pozycji znaku i ma określoną długość.

Substring(Int32)

Pobiera podciąg z tego wystąpienia. Podciąg zaczyna się od określonego położenia znaku i kontynuuje koniec ciągu.

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

Parametry

startIndex
Int32

Pozycja początkowego podciągu w tym wystąpieniu oparta na zera.

Zwraca

Ciąg, który jest odpowiednikiem podciągu rozpoczynającego się w startIndex tym wystąpieniu, lub Empty jeśli startIndex jest równy długości tego wystąpienia.

Wyjątki

startIndex jest mniejsza niż zero lub większa niż długość tego wystąpienia.

Przykłady

W poniższym przykładzie pokazano uzyskanie podciągu z ciągu.

using namespace System;
using namespace System::Collections;

int main()
{
   array<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:");
   for each (String^ s in info) 
      Console::WriteLine(s);

   Console::WriteLine("\nWe want to retrieve only the key information. That is:");
   for each (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
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

W poniższym przykładzie Substring użyto metody do oddzielenia par klucz/wartość rozdzielonych znakiem równości (=).

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'

Metoda IndexOf służy do pobierania pozycji znaku równości w ciągu. Wywołanie Substring(Int32, Int32) metody wyodrębnia nazwę klucza, która rozpoczyna się od pierwszego znaku w ciągu i rozszerza liczbę znaków zwracanych przez wywołanie metody IndexOf . Wywołanie Substring(Int32) metody wyodrębnia następnie wartość przypisaną do klucza. Zaczyna się od jednej pozycji znaku poza znakiem równości i rozszerza się na koniec ciągu.

Uwagi

Metoda wywołuje Substring(Int32) metodę w celu wyodrębnienia podciągów z ciągu rozpoczynającego się od określonego położenia znaku i kończy się na końcu ciągu. Pozycja znaku początkowego jest oparta na zerowym położeniu; innymi słowy, pierwszy znak w ciągu jest w indeksie 0, a nie indeks 1. Aby wyodrębnić podciąg rozpoczynający się od określonej pozycji znaku i kończy się przed końcem ciągu, wywołaj metodę Substring(Int32, Int32) .

Uwaga

Metoda ta nie modyfikuje wartości bieżącego wystąpienia. Zamiast tego zwraca nowy ciąg rozpoczynający się startIndex od pozycji w bieżącym ciągu.

Aby wyodrębnić podciąg rozpoczynający się od określonego znaku lub sekwencji znaków, wywołaj metodę, taką jak IndexOf lub IndexOf , aby uzyskać wartość startIndex. Drugi przykład ilustruje to; wyodrębnia wartość klucza, która rozpoczyna jedną pozycję znaku po = znaku.

Jeśli startIndex jest równa zero, metoda zwraca oryginalny ciąg bez zmian.

Zobacz też

Dotyczy

Substring(Int32, Int32)

Pobiera podciąg z tego wystąpienia. Podciąg zaczyna się od określonej pozycji znaku i ma określoną długość.

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

Parametry

startIndex
Int32

Pozycja początkowego podciągu w tym wystąpieniu oparta na zera.

length
Int32

Liczba znaków w podciągu.

Zwraca

Ciąg, który jest odpowiednikiem podciągu długości length rozpoczynającej się w startIndex tym wystąpieniu, lub Empty jeśli startIndex jest równy długości tego wystąpienia i length jest zerowy.

Wyjątki

startIndex plus length wskazuje pozycję, która nie mieści się w tym wystąpieniu.

-lub-

startIndex wartość lub length jest mniejsza niż zero.

Przykłady

Poniższy przykład ilustruje proste wywołanie Substring(Int32, Int32) metody, która wyodrębnia dwa znaki z ciągu rozpoczynającego się na szóstej pozycji znaku (czyli w indeksie pięć).

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

W poniższym przykładzie użyto Substring(Int32, Int32) metody w następujących trzech przypadkach do izolowania podciągów w ciągu. W dwóch przypadkach podciągy są używane w porównaniach, a w trzecim przypadku zgłaszany jest wyjątek, ponieważ określono nieprawidłowe parametry.

  • Wyodrębnia pojedynczy znak na trzecim miejscu w ciągu (w indeksie 2) i porównuje go z znakiem "c". To porównanie zwraca wartość true.

  • Wyodrębnia zero znaków rozpoczynających się na czwartej pozycji w ciągu (w indeksie 3) i przekazuje je do IsNullOrEmpty metody. Zwraca wartość true, ponieważ wywołanie Substring metody zwraca String.Emptywartość .

  • Próbuje wyodrębnić jeden znak rozpoczynający się na czwartej pozycji w ciągu. Ponieważ w tej pozycji nie ma znaku, wywołanie metody zgłasza ArgumentOutOfRangeException wyjątek.

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

W poniższym przykładzie Substring użyto metody do oddzielenia par klucz/wartość rozdzielonych znakiem równości (=).

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'

Metoda IndexOf służy do pobierania pozycji znaku równości w ciągu. Wywołanie Substring(Int32, Int32) metody wyodrębnia nazwę klucza, która rozpoczyna się od pierwszego znaku w ciągu i rozszerza liczbę znaków zwracanych przez wywołanie metody IndexOf . Wywołanie Substring(Int32) metody wyodrębnia następnie wartość przypisaną do klucza. Zaczyna się od jednej pozycji znaku poza znakiem równości i rozszerza się na koniec ciągu.

Uwagi

Metoda wywołuje Substring(Int32, Int32) metodę w celu wyodrębnienia podciągów z ciągu rozpoczynającego się od określonego położenia znaku i kończy się przed końcem ciągu. Pozycja znaku początkowego jest oparta na zerowym położeniu; innymi słowy, pierwszy znak w ciągu jest w indeksie 0, a nie indeks 1. Aby wyodrębnić podciąg rozpoczynający się od określonej pozycji znaku i kontynuuje koniec ciągu, wywołaj metodę Substring(Int32) .

Uwaga

Metoda ta nie modyfikuje wartości bieżącego wystąpienia. Zamiast tego zwraca nowy ciąg z znakami rozpoczynającymi length się od startIndex pozycji w bieżącym ciągu.

Parametr length reprezentuje całkowitą liczbę znaków wyodrębnianych z bieżącego wystąpienia ciągu. Obejmuje to znak początkowy znaleziony w indeksie startIndex. Innymi słowy, Substring metoda próbuje wyodrębnić znaki z indeksu do indeksu + startIndexstartIndexlength — 1.

Aby wyodrębnić podciąg rozpoczynający się od określonego znaku lub sekwencji znaków, wywołaj metodę, taką jak IndexOf lub LastIndexOf , aby uzyskać wartość startIndex.

Jeśli podciąg powinien rozciągać się od startIndex do określonej sekwencji znaków, możesz wywołać metodę, taką jak IndexOf lub LastIndexOf , aby uzyskać indeks znaku końcowego lub sekwencji znaków. Następnie możesz przekonwertować wartość na pozycję indeksu w ciągu w następujący sposób:

  • Jeśli wyszukano pojedynczy znak, który ma oznaczać koniec podciągu, length parametr jest równy - startIndexendIndex+ 1, gdzie endIndex jest zwracaną wartością IndexOf metody lub.LastIndexOf Poniższy przykład wyodrębnia ciągły blok znaków "b" z ciągu.

    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
    
  • Jeśli wyszukano wiele znaków, które mają oznaczać koniec podciągów, length parametr jest równy - endMatchLengthendIndexstartIndex + , gdzie endIndex jest wartością IndexOf zwracaną metody lub LastIndexOf i endMatchLength jest długością sekwencji znaków, która oznacza koniec podciągów. Poniższy przykład wyodrębnia blok tekstu, który zawiera element 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>
    
  • Jeśli znak lub sekwencja znaków nie jest uwzględniona na końcu podciągu, length parametr jest równy endIndex - startIndex, gdzie endIndex jest zwracaną wartością IndexOf metody lub LastIndexOf .

Jeśli startIndex jest równa zero i length równa długości bieżącego ciągu, metoda zwraca oryginalny ciąg bez zmian.

Zobacz też

Dotyczy