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

String

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 montre comment obtenir 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
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'
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 récupérer la position du caractère égal dans la chaîne. L’appel à la Substring(Int32, Int32) méthode extrait le nom de 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 assignée à la clé. Elle 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 du caractère de début est un de base zéro ; en d’autres termes, le premier caractère de la chaîne est à 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 l’instance actuelle. Au lieu de cela, elle retourne une nouvelle chaîne qui commence à la startIndex position dans la chaîne actuelle.

Pour extraire une sous-chaîne qui commence par un caractère ou une séquence de caractères spécifique, 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

String

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 en commençant à la position du 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
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 dans 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 car des paramètres non valides sont spécifiés.

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

  • Il extrait zéro caractère à partir de la quatrième position de la chaîne (à l’index 3) et le passe à la IsNullOrEmpty méthode. Cela retourne la valeur true, car l’appel à la Substring méthode retourne String.Empty .

  • Il tente d’extraire un caractère à partir de la quatrième position de la chaîne. Étant donné qu’il n’y a pas de 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
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'
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 récupérer la position du caractère égal dans la chaîne. L’appel à la Substring(Int32, Int32) méthode extrait le nom de 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 assignée à la clé. Elle 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 du caractère de début est un de base zéro ; en d’autres termes, le premier caractère de la chaîne est à 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 l’instance actuelle. Au lieu de cela, elle retourne une nouvelle chaîne avec des length caractères commençant à la startIndex position dans la chaîne actuelle.

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

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

Si la sous-chaîne s’étend 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 effectué une recherche sur un caractère unique pour marquer la fin de la sous-chaîne, le length paramètre est égal à endIndex - startIndex + 1, où endIndex est la valeur de retour de la IndexOf IndexOf méthode ou. L’exemple suivant extrait un bloc continu de caractères « b » à partir 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
    
    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 à endIndex + endMatchLength - startIndex , où endIndex est la valeur de retour de la IndexOf IndexOf méthode ou, et endMatchLength est 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>
    
    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 à la fin de la sous-chaîne, le length paramètre est égal à endIndex - startIndex , où endIndex est la valeur de retour de la IndexOf IndexOf méthode ou.

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

Voir aussi

S’applique à