String.Substring Méthode

Définition

Récupère une sous-chaîne de cette instance.

Ce membre est surchargé. Pour obtenir des informations complètes sur ce membre, y compris sa syntaxe, son utilisation et des exemples s'y rapportant, cliquez sur un nom dans la liste de surcharge.

Surcharges

Substring(Int32)

Récupère une sous-chaîne de cette instance. La sous-chaîne commence à une position de caractère spécifiée et continue jusqu'à la fin de la chaîne.

Substring(Int32, Int32)

Récupère une sous-chaîne de cette instance. La sous-chaîne commence à une position de caractère spécifiée et sa longueur est définie.

Substring(Int32)

Récupère une sous-chaîne de cette instance. La sous-chaîne commence à une position de caractère spécifiée et continue jusqu'à la fin de la chaîne.

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ètres

startIndex
Int32

Position de caractère de départ de base zéro d'une sous-chaîne dans cette instance.

Retours

Chaîne équivalente à la sous-chaîne qui commence à startIndex dans cette instance ou Empty si startIndex est égal à la longueur de cette instance.

Exceptions

startIndex est inférieur à zéro ou supérieur à la longueur de cette instance.

Exemples

L’exemple suivant illustre l’obtention d’une sous-chaîne à partir d’une chaîne.

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

L’exemple suivant utilise la Substring méthode pour séparer les paires clé/valeur qui sont délimitées par un caractère égal à (=).

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'

La IndexOf méthode est utilisée pour obtenir la position du caractère égal dans la chaîne. L’appel à la Substring(Int32, Int32) méthode extrait le nom de la clé, qui commence à partir du premier caractère de la chaîne et s’étend pour le nombre de caractères retournés par l’appel à la IndexOf méthode. L’appel à la Substring(Int32) méthode extrait ensuite la valeur affectée à la clé. Il commence à une position de caractère au-delà du caractère égal et s’étend jusqu’à la fin de la chaîne.

Remarques

Vous appelez la Substring(Int32) méthode pour extraire une sous-chaîne d’une chaîne qui commence à une position de caractère spécifiée et se termine à la fin de la chaîne. La position de début du caractère est de base zéro ; en d’autres termes, le premier caractère de la chaîne se trouve à l’index 0, et non à l’index 1. Pour extraire une sous-chaîne qui commence à une position de caractère spécifiée et se termine avant la fin de la chaîne, appelez la Substring(Int32, Int32) méthode .

Notes

Cette méthode ne modifie pas la valeur de la instance actuelle. Au lieu de cela, il retourne une nouvelle chaîne qui commence à la startIndex position dans la chaîne active.

Pour extraire une sous-chaîne qui commence par un caractère ou une séquence de caractères particulier, appelez une méthode telle que IndexOf ou IndexOf pour obtenir la valeur de startIndex. Le deuxième exemple illustre cela ; il extrait une valeur de clé qui commence une position de caractère après le = caractère.

Si startIndex est égal à zéro, la méthode retourne la chaîne d’origine inchangée.

Voir aussi

S’applique à

Substring(Int32, Int32)

Récupère une sous-chaîne de cette instance. La sous-chaîne commence à une position de caractère spécifiée et sa longueur est définie.

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ètres

startIndex
Int32

Position de caractère de départ de base zéro d'une sous-chaîne dans cette instance.

length
Int32

Nombre de caractères dans la sous-chaîne.

Retours

Chaîne équivalente à la sous-chaîne de longueur length qui commence à startIndex dans cette instance ou Empty si startIndex est égal à la longueur de cette instance et length a la valeur zéro.

Exceptions

startIndex plus length indique une position qui n’est pas dans cette instance.

- ou -

startIndex ou length est inférieur à zéro.

Exemples

L’exemple suivant illustre un appel simple à la Substring(Int32, Int32) méthode qui extrait deux caractères d’une chaîne commençant à la position de sixième caractère (c’est-à-dire à l’index cinq).

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

L’exemple suivant utilise la Substring(Int32, Int32) méthode dans les trois cas suivants pour isoler les sous-chaînes au sein d’une chaîne. Dans deux cas, les sous-chaînes sont utilisées dans les comparaisons, et dans le troisième cas, une exception est levée parce que des paramètres non valides sont spécifiés.

  • Il extrait le caractère unique à la troisième position de la chaîne (à l’index 2) et le compare à un « c ». Cette comparaison retourne true.

  • Il extrait zéro caractères en commençant à la quatrième position de la chaîne (à l’index 3) et le transmet à la IsNullOrEmpty méthode. Cette propriété retourne true, car l’appel à la Substring méthode retourne String.Empty.

  • Il tente d’extraire un caractère en commençant à la quatrième position de la chaîne. Étant donné qu’il n’y a aucun caractère à cette position, l’appel de méthode lève une ArgumentOutOfRangeException exception.

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

L’exemple suivant utilise la Substring méthode pour séparer les paires clé/valeur qui sont délimitées par un caractère égal à (=).

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'

La IndexOf méthode est utilisée pour obtenir la position du caractère égal dans la chaîne. L’appel à la Substring(Int32, Int32) méthode extrait le nom de la clé, qui commence à partir du premier caractère de la chaîne et s’étend pour le nombre de caractères retournés par l’appel à la IndexOf méthode. L’appel à la Substring(Int32) méthode extrait ensuite la valeur affectée à la clé. Il commence à une position de caractère au-delà du caractère égal et s’étend jusqu’à la fin de la chaîne.

Remarques

Vous appelez la Substring(Int32, Int32) méthode pour extraire une sous-chaîne d’une chaîne qui commence à une position de caractère spécifiée et se termine avant la fin de la chaîne. La position de début du caractère est de base zéro ; en d’autres termes, le premier caractère de la chaîne se trouve à l’index 0, et non à l’index 1. Pour extraire une sous-chaîne qui commence à une position de caractère spécifiée et continue jusqu’à la fin de la chaîne, appelez la Substring(Int32) méthode .

Notes

Cette méthode ne modifie pas la valeur de la instance actuelle. Au lieu de cela, il retourne une nouvelle chaîne avec length des caractères à partir de la startIndex position dans la chaîne actuelle.

Le length paramètre représente le nombre total de caractères à extraire de la chaîne actuelle instance. Cela inclut le caractère de départ trouvé dans l’index startIndex. En d’autres termes, la Substring méthode tente d’extraire des caractères d’index startIndex en index startIndex + length - 1.

Pour extraire une sous-chaîne qui commence par un caractère ou une séquence de caractères particulier, appelez une méthode telle que IndexOf ou LastIndexOf pour obtenir la valeur de startIndex.

Si la sous-chaîne doit s’étendre de startIndex à une séquence de caractères spécifiée, vous pouvez appeler une méthode telle que IndexOf ou LastIndexOf pour obtenir l’index du caractère de fin ou de la séquence de caractères. Vous pouvez ensuite convertir cette valeur en position d’index dans la chaîne comme suit :

  • Si vous avez recherché un caractère unique qui doit marquer la fin de la sous-chaîne, le length paramètre est égal endIndexstartIndex - à + 1, où endIndex est la valeur de retour de la IndexOf méthode ou.LastIndexOf L’exemple suivant extrait un bloc continu de caractères « b » d’une chaîne.

    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
    
  • Si vous avez recherché plusieurs caractères qui doivent marquer la fin de la sous-chaîne, le length paramètre est égal - + startIndexendMatchLengthendIndex à , où endIndex est la valeur de retour de la IndexOf méthode ou LastIndexOf et endMatchLength à la longueur de la séquence de caractères qui marque la fin de la sous-chaîne. L’exemple suivant extrait un bloc de texte qui contient un élément 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>
    
  • Si le caractère ou la séquence de caractères n’est pas inclus dans la fin de la sous-chaîne, le length paramètre est égal à endIndexstartIndex - , où endIndex est la valeur de retour de la IndexOf méthode ou .LastIndexOf

Si startIndex est égal à zéro et length est égal à la longueur de la chaîne actuelle, la méthode retourne la chaîne d’origine inchangée.

Voir aussi

S’applique à