String.Substring Metoda
Definice
Důležité
Některé informace platí pro předběžně vydaný produkt, který se může zásadně změnit, než ho výrobce nebo autor vydá. Microsoft neposkytuje žádné záruky, výslovné ani předpokládané, týkající se zde uváděných informací.
Načte podřetěr z této instance.
Tento člen je přetížen. Úplné informace o tomto členu, včetně syntaxe, použití a příkladů, potřebujete kliknout na název v seznamu přetížení.
Přetížení
| Name | Description |
|---|---|
| Substring(Int32) |
Načte podřetěr 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ěr z této instance. Podřetětěr začíná na zadané pozici znaku a má zadanou délku. |
Substring(Int32)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Načte podřetěr 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 založeného na nule podřetězdce v této instanci.
Návraty
Řetězec, který je ekvivalentní podřetězci, který začíná startIndex v této instanci, nebo Empty je-li startIndex roven 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.
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, které jsou oddělené znakem equals (=).
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 rovná se znak v řetězci. Volání Substring(Int32, Int32) metody extrahuje název klíče, který začíná od prvního znaku v řetězci a rozšiřuje počet znaků vrácených voláním metody IndexOf . Volání Substring(Int32) metody pak extrahuje hodnotu přiřazenou klíči. Začíná na jedné pozici znaku nad rovnou znakem a rozšiřuje se na konec řetězce.
Poznámky
Zavoláte metodu Substring(Int32) pro extrakci podřetězce z řetězce, který začíná na zadané pozici znaku a končí na konci řetězce. Počáteční pozice znaku je založená na nule; Jinými slovy, první znak v řetězci je v indexu 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) .
Note
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, například IndexOf nebo IndexOf získat hodnotu startIndex. Druhý příklad to ilustruje; Extrahuje hodnotu klíče, která za znakem začíná jednu pozici znaku = .
Pokud startIndex je rovna nule, metoda vrátí původní řetězec beze změny.
Viz také
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Split(Char[])
- Trim(Char[])
Platí pro
Substring(Int32, Int32)
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
- Zdroj:
- String.Manipulation.cs
Načte podřetěr z této instance. Podřetětěr 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 založeného na nule podřetězdce v této instanci.
- length
- Int32
Počet znaků v podřetědci.
Návraty
Řetězec, který je ekvivalentní podřetězci délky length , která začíná startIndex v této instanci, nebo Empty je-li startIndex rovna 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 ukazuje jednoduché volání Substring(Int32, Int32) metody, která extrahuje dva znaky z řetězce začínajícího 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 řetězci. Ve dvou případech se v porovnání používají podřetězy 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 písmenem "c". Toto porovnání vrátí
true.Extrahuje nula znaků počínaje čtvrtou pozicí v řetězci (v indexu 3) a předá ji IsNullOrEmpty metodě. Vrátí hodnotu true, protože volání Substring metody vrátí String.Empty.
Pokusí se extrahovat jeden znak počínaje čtvrtou pozicí v řetězci. Vzhledem k tomu, že na této pozici není žádný znak, volání metody vyvolá ArgumentOutOfRangeException 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, které jsou oddělené znakem equals (=).
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 rovná se znak v řetězci. Volání Substring(Int32, Int32) metody extrahuje název klíče, který začíná od prvního znaku v řetězci a rozšiřuje počet znaků vrácených voláním metody IndexOf . Volání Substring(Int32) metody pak extrahuje hodnotu přiřazenou klíči. Začíná na jedné pozici znaku nad rovnou znakem a rozšiřuje se na konec řetězce.
Poznámky
Zavoláte metodu Substring(Int32, Int32) pro extrakci podřetězce z řetězce, který začíná na zadané pozici znaku a končí před koncem řetězce. Počáteční pozice znaku je založená na nule; Jinými slovy, první znak v řetězci je v indexu 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) .
Note
Tato metoda neupravuje hodnotu aktuální instance. Místo toho vrátí nový řetězec se length znaky začínajícími od startIndex pozice v aktuálním řetězci.
Parametr length představuje celkový počet znaků, které se mají extrahovat z aktuální instance ř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, například IndexOf nebo LastIndexOf získat hodnotu startIndex.
Pokud by se podřetězec měl rozšířit od startIndex zadané sekvence znaků, můžete volat metodu, jako IndexOf je nebo LastIndexOf získat index koncového znaku nebo sekvence znaků. Tuto hodnotu pak můžete převést na pozici indexu v řetězci následujícím způsobem:
Pokud jste hledali jeden znak, který má označit konec podřetětědce,
lengthparametr se rovnáendIndex-startIndex+ 1, kdeendIndexje návratová IndexOf hodnota nebo LastIndexOf metoda. 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) = bbblet 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) = bbbModule 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) = bbbPokud jste hledali více znaků, které mají označit konec podřetědce,
lengthparametr se rovnáendIndex+endMatchLength-startIndex, kdeendIndexje návratová IndexOf hodnota nebo LastIndexOf metoda, aendMatchLengthje délka sekvence znaků, která označuje konec podřetětědce. 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í zahrnuta na konci podřetěděce,
lengthparametr se rovnáendIndex-startIndex, kdeendIndexje návratová IndexOf hodnota metody nebo LastIndexOf metody.
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.