String.Substring Metoda

Definice

Načte podřetězec z této instance.

Tento člen je přetížen. Podrobnější informace o tomto členu, včetně syntaxe, způsobu použití a příkladů, získáte kliknutím na název v seznamu přetížení.

Přetížení

Substring(Int32)

Načte podřetězec z této instance. Podřetězce začíná na zadané pozici znaku a pokračuje na konec řetězce.

Substring(Int32, Int32)

Načte podřetězec z této instance. Podřetězení začíná na zadané pozici znaku a má zadanou délku.

Substring(Int32)

Načte podřetězec z této instance. Podřetězce začíná na zadané pozici znaku a pokračuje na konec řetězce.

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

Pozice počátečního znaku od nuly podřetězení v tomto případě.

Návraty

Řetězec, který je ekvivalentní podřetězce, který začíná v startIndex tomto případě, nebo Empty pokud startIndex se rovná délce této instance.

Výjimky

startIndex je menší než nula nebo větší než délka této instance.

Příklady

Následující příklad ukazuje získání podřetězce z řetězce.

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

Následující příklad používá metodu Substring k oddělení párů klíč/hodnota oddělených znakem rovná se (=).

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 se používá k získání pozice znaku rovná se v řetězci. Volání Substring(Int32, Int32) metody extrahuje název klíče, který začíná prvním znakem v řetězci a rozšiřuje počet znaků vrácených voláním IndexOf metody . Volání Substring(Int32) metody pak extrahuje hodnotu přiřazenou klíči. Začíná na pozici jednoho znaku za znakem rovná se a přesahuje na konec řetězce.

Poznámky

Voláním Substring(Int32) metody extrahujete podřetězce z řetězce, který začíná na zadané pozici znaku a končí na konci řetězce. Pozice počátečního znaku je založena na nule; Jinými slovy, první znak v řetězci má index 0, nikoli index 1. Chcete-li extrahovat podřetězce, který začíná na zadané pozici znaku a končí před koncem řetězce, zavolejte metodu Substring(Int32, Int32) .

Poznámka

Tato metoda neupravuje hodnotu aktuální instance. Místo toho vrátí nový řetězec, který začíná na startIndex pozici v aktuálním řetězci.

Chcete-li extrahovat podřetězce, který začíná určitým znakem nebo posloupností znaků, zavolejte metodu, jako IndexOfIndexOf je nebo, abyste získali hodnotu startIndex. Druhý příklad to ilustruje; extrahuje hodnotu klíče, která začíná o jednu pozici znaku za znakem = .

Pokud startIndex se rovná nule, vrátí metoda původní řetězec beze změny.

Viz také

Platí pro

Substring(Int32, Int32)

Načte podřetězec z této instance. Podřetězení začíná na zadané pozici znaku a má zadanou délku.

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

Pozice počátečního znaku od nuly podřetězení v tomto případě.

length
Int32

Počet znaků v podřetěžci.

Návraty

Řetězec, který je ekvivalentní podřetězce délky length , která začíná startIndex v tomto případě, nebo Empty pokud startIndex se rovná délce této instance a length je nula.

Výjimky

startIndex plus length označuje pozici, která není v této instanci.

-nebo-

startIndex nebo length je menší než nula.

Příklady

Následující příklad znázorňuje jednoduché volání Substring(Int32, Int32) metody, která extrahuje dva znaky z řetězce, který začíná na šesté pozici znaku (to znamená na indexu pět).

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

Následující příklad používá metodu Substring(Int32, Int32) v následujících třech případech k izolaci podřetězců v rámci řetězce. Ve dvou případech se při porovnávání používají podřetězdce a ve třetím případě je vyvolán výjimka, protože jsou zadány neplatné parametry.

  • Extrahuje jeden znak na třetí pozici v řetězci (v indexu 2) a porovná ho s "c". Toto porovnání vrátí true.

  • Extrahuje nula znaků počínaje čtvrtou pozicí v řetězci (na indexu 3) a předá ho IsNullOrEmpty metodě. Vrátí hodnotu true, protože volání Substring metody vrátí String.Emptyhodnotu .

  • Pokusí se extrahovat jeden znak začínající na čtvrté pozici v řetězci. Vzhledem k tomu, že na této pozici není žádný znak, vyvolá volání ArgumentOutOfRangeException metody výjimku.

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

Následující příklad používá metodu Substring k oddělení párů klíč/hodnota oddělených znakem rovná se (=).

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 se používá k získání pozice znaku rovná se v řetězci. Volání Substring(Int32, Int32) metody extrahuje název klíče, který začíná prvním znakem v řetězci a rozšiřuje počet znaků vrácených voláním IndexOf metody . Volání Substring(Int32) metody pak extrahuje hodnotu přiřazenou klíči. Začíná na pozici jednoho znaku za znakem rovná se a přesahuje na konec řetězce.

Poznámky

Voláním Substring(Int32, Int32) metody extrahujete podřetězce z řetězce, který začíná na zadané pozici znaku a končí před koncem řetězce. Pozice počátečního znaku je založena na nule; Jinými slovy, první znak v řetězci má index 0, nikoli index 1. Chcete-li extrahovat podřetězce, který začíná na zadané pozici znaku a pokračuje na konec řetězce, zavolejte metodu Substring(Int32) .

Poznámka

Tato metoda neupravuje hodnotu aktuální instance. Místo toho vrátí nový řetězec se length znaky začínajícími startIndex od pozice v aktuálním řetězci.

Parametr length představuje celkový počet znaků, které se mají extrahovat z instance aktuálního řetězce. To zahrnuje počáteční znak nalezený v indexu startIndex. Jinými slovy, Substring metoda se pokusí extrahovat znaky z indexu startIndex do indexu startIndex + length – 1.

Chcete-li extrahovat podřetězce, který začíná určitým znakem nebo posloupností znaků, zavolejte metodu, jako IndexOfLastIndexOf je nebo, abyste získali hodnotu startIndex.

Pokud má podřetězce přesahovat z startIndex na zadanou sekvenci znaků, můžete volat metodu, jako IndexOf je nebo , LastIndexOf abyste získali index koncového znaku nebo sekvence znaků. Tuto hodnotu pak můžete následujícím způsobem převést na pozici indexu v řetězci:

  • Pokud jste hledali jeden znak, který má označit konec podřetěžce, length parametr se rovná - startIndexendIndex+ 1, kde endIndex je návratová IndexOf hodnota metody nebo .LastIndexOf Následující příklad extrahuje souvislý blok znaků "b" z řetězce.

    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
    
  • Pokud jste hledali více znaků, které mají označit konec podřetětce, length parametr se rovná - endMatchLengthendIndex + startIndex , kde endIndex je návratová hodnota IndexOf metody nebo LastIndexOf a endMatchLength je délka sekvence znaků, která označuje konec podřetětce. Následující příklad extrahuje blok textu, který obsahuje 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>
    
  • Pokud znak nebo sekvence znaků není na konci podřetětěce, length parametr se rovná endIndexstartIndex - , kde endIndex je návratová IndexOf hodnota metody nebo .LastIndexOf

Pokud startIndex se rovná nule a length rovná se délce aktuálního řetězce, vrátí metoda původní řetězec beze změny.

Viz také

Platí pro