String.Substring Metódus

Definíció

Lekéri az alsztringet ebből a példányból.

Ez a tag túlterhelt. A tagra vonatkozó teljes körű információkért, beleértve a szintaxist, a használatot és a példákat, kattintson egy névre a túlterhelési listában.

Túlterhelések

Name Description
Substring(Int32)

Lekéri az alsztringet ebből a példányból. Az alsztring egy megadott karakterhelyzetben kezdődik, és a sztring végéig tart.

Substring(Int32, Int32)

Lekéri az alsztringet ebből a példányból. Az alsztring egy megadott karakterhelyzetben kezdődik, és meghatározott hosszúságú.

Substring(Int32)

Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs

Lekéri az alsztringet ebből a példányból. Az alsztring egy megadott karakterhelyzetben kezdődik, és a sztring végéig tart.

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

Paraméterek

startIndex
Int32

Az alsztring nulla alapú kezdő karakterpozíciója ebben a példányban.

Válaszok

Olyan sztring, amely egyenértékű az ebben a példányban kezdődő startIndex részsztringgel, vagy Empty ha startIndex megegyezik a példány hosszával.

Kivételek

startIndex kisebb, mint nulla vagy nagyobb, mint a példány hossza.

Példák

Az alábbi példa bemutatja, hogy egy sztringből lekérhető egy részsztring.

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

Az alábbi példa a Substring metódussal választja el az egyenlő (=) karakterekkel tagolt kulcs-/érték párokat.

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'

A IndexOf metódus az egyenlőségjel pozíciójának lekérésére szolgál a sztringben. A metódus hívása Substring(Int32, Int32) kinyeri a kulcs nevét, amely a sztring első karakterétől indul, és a metódushoz való hívás által visszaadott karakterek számát is kiterjeszti IndexOf . A metódus hívása Substring(Int32) ezután kinyeri a kulcshoz rendelt értéket. Egy karakterrel kezdődik az egyenlőségjelen túl, és a sztring végéig terjed.

Megjegyzések

A metódust Substring(Int32) úgy hívhatja meg, hogy kinyerjen egy sztringrészt egy adott karakterhelyzetben kezdődő és a sztring végén végződő sztringből. A kezdő karakter pozíciója nulla alapú; más szóval a sztring első karaktere a 0 indexnél van, nem az 1. indexnél. Ha egy adott karakterhelyzetben kezdődő és a sztring vége előtt végződő részsztringet szeretne kinyerni, hívja meg a metódust Substring(Int32, Int32) .

Note

Ez a metódus nem módosítja az aktuális példány értékét. Ehelyett egy új sztringet ad vissza, amely az aktuális sztring startIndex helyén kezdődik.

Ha egy adott karakterrel vagy karaktersorozattal kezdődő részszűrést szeretne kinyerni, hívjon meg egy metódust, például IndexOfIndexOf vagy kérje le az értékét startIndex. A második példa ezt szemlélteti; egy kulcsértéket nyer ki, amely egy karakterrel kezdődik a = karakter után.

Ha startIndex nullával egyenlő, a metódus az eredeti sztringet változatlanul adja vissza.

Lásd még

A következőre érvényes:

Substring(Int32, Int32)

Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs
Forrás:
String.Manipulation.cs

Lekéri az alsztringet ebből a példányból. Az alsztring egy megadott karakterhelyzetben kezdődik, és meghatározott hosszúságú.

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

Paraméterek

startIndex
Int32

Az alsztring nulla alapú kezdő karakterpozíciója ebben a példányban.

length
Int32

Az alsztringben lévő karakterek száma.

Válaszok

Olyan sztring, amely egyenértékű az ebben a példányban kezdődő hossz length részszúrásával, vagy startIndex ha Empty egyenlő a példány hosszával, és startIndexlength nulla.

Kivételek

startIndex plusz length egy nem ebben a példányban lévő pozíciót jelez.

-vagy-

startIndex vagy length kisebb, mint nulla.

Példák

Az alábbi példa egy egyszerű hívást mutat be a Substring(Int32, Int32) metódushoz, amely két karaktert nyer ki egy sztringből a hatodik karakterpozíciótól kezdve (azaz az öt. indexnél).

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

Az alábbi példa a következő három esetben használja a Substring(Int32, Int32) metódust egy sztringen belüli részsztringek elkülönítésére. Két esetben az alsztringeket az összehasonlítások használják, a harmadik esetben kivételt adnak ki, mert érvénytelen paraméterek vannak megadva.

  • Kinyeri az egyetlen karaktert a sztring harmadik helyén (a 2. indexnél), és összehasonlítja a "c" karakterrel. Ez az összehasonlítás eredménye true.

  • Nulla karaktert nyer ki a sztring negyedik pozíciójától kezdve (a 3. indexnél), és átadja a IsNullOrEmpty metódusnak. Ez igaz értéket ad vissza, mert a metódus hívása SubstringString.Emptyad vissza.

  • Egy karaktert próbál kinyerni a sztring negyedik pozíciójától kezdve. Mivel ebben a pozícióban nincs karakter, a metódushívás kivételt ArgumentOutOfRangeException jelez.

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

Az alábbi példa a Substring metódussal választja el az egyenlő (=) karakterekkel tagolt kulcs-/érték párokat.

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'

A IndexOf metódus az egyenlőségjel pozíciójának lekérésére szolgál a sztringben. A metódus hívása Substring(Int32, Int32) kinyeri a kulcs nevét, amely a sztring első karakterétől indul, és a metódushoz való hívás által visszaadott karakterek számát is kiterjeszti IndexOf . A metódus hívása Substring(Int32) ezután kinyeri a kulcshoz rendelt értéket. Egy karakterrel kezdődik az egyenlőségjelen túl, és a sztring végéig terjed.

Megjegyzések

A metódust Substring(Int32, Int32) úgy hívhatja meg, hogy kinyerjen egy sztringrészt egy adott karakterhelyzetben kezdődő és a sztring vége előtt végződő sztringből. A kezdő karakter pozíciója nulla alapú; más szóval a sztring első karaktere a 0 indexnél van, nem az 1. indexnél. Ha egy adott karakterhelyzetben kezdődő és a sztring végéig tartó alsztringet szeretne kinyerni, hívja meg a metódust Substring(Int32) .

Note

Ez a metódus nem módosítja az aktuális példány értékét. Ehelyett egy új sztringet ad vissza, amelynek length karakterei az aktuális sztringben startIndex lévő pozícióból indulnak ki.

A length paraméter az aktuális sztringpéldányból kinyerni kívánt karakterek teljes számát jelöli. Ide tartozik az indexben startIndextalálható kezdő karakter. Más szóval a metódus megpróbálja kinyerni a Substring karaktereket az indexből startIndex az indexbe startIndex + length – 1.

Ha egy adott karakterrel vagy karaktersorozattal kezdődő részszűrést szeretne kinyerni, hívjon meg egy metódust, például IndexOfLastIndexOf vagy kérje le az értékét startIndex.

Ha az alsztringnek egy adott karaktersorozatra startIndex kell terjednie, meghívhat egy metódust, például IndexOf a záró karakter vagy LastIndexOf a karaktersorozat indexét. Ezt az értéket ezután a következőképpen alakíthatja át indexpozícióvá a sztringben:

  • Ha egyetlen karaktert keresett, amely az alsztring végét jelöli, a length paraméter értékeendIndex - startIndex+ 1, ahol endIndex a metódus IndexOf visszatérési LastIndexOf értéke. Az alábbi példa egy "b" karakterből álló folyamatos blokkot nyer ki egy sztringből.

    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
    
  • Ha több karaktert keresett, amelyek az alsztring végét jelölik, akkor a length paraméter egyenlőendIndex + endMatchLength - startIndex , ahol endIndex az vagy IndexOf a metódus visszatérési LastIndexOf értéke, és endMatchLength az alsztring végét jelző karaktersorozat hossza. Az alábbi példa egy XML-elemet <definition> tartalmazó szövegblokkot nyer ki.

    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>
    
  • Ha a karakter- vagy karaktersorozat nem szerepel az alsztring végén, a length paraméter egyenlő endIndex - startIndex, ahol endIndex a metódus visszatérési IndexOfLastIndexOf értéke.

Ha startIndex nullával egyenlő, és length az aktuális sztring hosszával egyenlő, akkor a metódus változatlanul adja vissza az eredeti sztringet.

Lásd még

A következőre érvényes: