String.Substring Méthode
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Récupère une sous-chaîne de cette instance.
Ce membre est surchargé. Pour obtenir des informations complètes sur ce membre, notamment la syntaxe, l’utilisation et les exemples, cliquez sur un nom dans la liste de surcharge.
Surcharges
| Nom | Description |
|---|---|
| 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 à 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 a une longueur spécifiée. |
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 à 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 elle est égale à 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.
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 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 à 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épart est 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.
Note
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 particulier, appelez une méthode telle que IndexOf ou IndexOf pour obtenir la valeur de startIndex. Le deuxième exemple illustre ceci ; il extrait une valeur de clé qui commence une position de caractère après le = caractère.
Si startIndex elle est égale à zéro, la méthode retourne la chaîne d’origine inchangée.
Voir aussi
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Split(Char[])
- Trim(Char[])
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 a une longueur spécifiée.
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 elle startIndex est égale à la longueur de cette instance et length est égale à zéro.
Exceptions
startIndex plus length indique une position non comprise 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 sixième position de caractère (autrement dit, à 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 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 les 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 commençant à la quatrième position de la chaîne (à l’index 3) et le transmet à la IsNullOrEmpty méthode. Cette propriété renvoie la valeur true, car l’appel à la Substring méthode retourne String.Empty.
Il tente d’extraire un caractère commençant à la quatrième position de la chaîne. Étant donné qu’il n’existe 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 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 à 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épart est 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 à la fin de la chaîne, appelez la Substring(Int32) méthode.
Note
Cette méthode ne modifie pas la valeur de l’instance actuelle. Au lieu de cela, elle retourne une nouvelle chaîne avec length des caractères commençant par la startIndex position dans la chaîne active.
Le length paramètre représente le nombre total de caractères à extraire de l’instance de chaîne actuelle. Cela inclut 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 à l’index + startIndexstartIndexlength - 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 d’à startIndex une séquence de caractères spécifiée, vous pouvez appeler une méthode telle que IndexOf ou LastIndexOf 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
lengthparamètre est égalendIndexstartIndex- à + 1, oùendIndexest la valeur de retour de la ou LastIndexOf de la IndexOf méthode. 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) = 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) = bbbSi vous avez recherché plusieurs caractères qui doivent marquer la fin de la sous-chaîne, le
lengthparamètre est égal -endMatchLength+endIndexstartIndexà laendIndexvaleur de retour de la ou LastIndexOf de la IndexOf méthode, etendMatchLengthla 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
lengthparamètre est égalendIndex-startIndexà , oùendIndexest la valeur de retour de la ou LastIndexOf de la IndexOf méthode.
Si startIndex elle est égale à zéro et length égale à la longueur de la chaîne actuelle, la méthode retourne la chaîne d’origine inchangée.