Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

String.Substring méthode (Int32, Int32)

 

Date de publication : juillet 2016

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.

Espace de noms:   System
Assembly:  mscorlib (dans mscorlib.dll)

public string Substring(
	int startIndex,
	int length
)

Paramètres

startIndex
Type: System.Int32

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

length
Type: System.Int32

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

Valeur de retour

Type: System.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.

Exception Condition
ArgumentOutOfRangeException

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

ou

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

You call the M:System.String.Substring(System.Int32,System.Int32) method to extract a substring from a string that begins at a specified character position and ends before the end of the string. The starting character position is a zero-based; in other words, the first character in the string is at index 0, not index 1. To extract a substring that begins at a specified character position and continues to the end of the string, call the M:System.String.Substring(System.Int32) method.

System_CAPS_noteRemarque

This method does not modify the value of the current instance. Instead, it returns a new string with length characters starting from the startIndex position in the current string.

The length parameter represents the total number of characters to extract from the current string instance. This includes the starting character found at index startIndex. In other words, the M:System.String.Substring(System.Int32,System.Int32) method attempts to extract characters from index startIndex to index startIndex + length - 1.

To extract a substring that begins with a particular character or character sequence, call a method such as Overload:System.String.IndexOf or Overload:System.String.LastIndexOf to get the value of startIndex.

If the substring extends from startIndex to a specified character sequence, you can call a method such as Overload:System.String.IndexOf or Overload:System.String.LastIndexOf to get the index of the ending character or character sequence. You can then convert that value to an index position in the string as follows:

  • If you've searched for a single character that is to mark the end of the substring, the length parameter equals endIndex - startIndex + 1, where endIndex is the return value of the Overload:System.String.IndexOf or Overload:System.String.IndexOf method. The following example extracts a continuous block of "b" characters from a string.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          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
    
  • If you've searched for multiple characters that are to mark the end of the substring, the length parameter equals endIndex + endMatchLength - startIndex, where endIndex is the return value of the Overload:System.String.IndexOf or Overload:System.String.IndexOf method., and endMatchLength is the length of the character sequence that marks the end of the substring. The following example extracts a block of text that contains an XML <definition> element.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          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>
    
  • If the character or character sequence is not included in the end of the substring, the length parameter equals endIndex - startIndex, where endIndex is the return value of the Overload:System.String.IndexOf or Overload:System.String.IndexOf method.

If startIndex is equal to zero and equals the length of the current string, the method returns the original string unchanged.

The following example illustrates a simple call to the M:System.String.Substring(System.Int32,System.Int32) method that extracts two characters from a string starting at the sixth character position (that is, at index five).

using System;

public class Example
{
   public static void Main()
   {
      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

The following example uses the M:System.String.Substring(System.Int32,System.Int32) method in the following three cases to isolate substrings within a string. In two cases the substrings are used in comparisons, and in the third case an exception is thrown because invalid parameters are specified.

  • It extracts the single character and the third position in the string (at index 2) and compares it with a "c". This comparison returns true.

  • It extracts zero characters starting at the fourth position in the string (at index 3) and passes it to the M:System.String.IsNullOrEmpty(System.String) method. This returns true because the call to the M:System.String.Substring(System.Int32,System.Int32) method returns F:System.String.Empty.

  • It attempts to extract one character starting at the fourth position in the string. Because there is no character at that position, the method call throws an T:System.ArgumentOutOfRangeException exception.

using System;

public class Sample
{
   public static void Main() {
      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

The following example uses the Overload:System.String.Substring method to separate key/value pairs that are delimited by an equals ("=") character.

using System;

public class Example
{
   public static void Main()
   {
      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'

The M:System.String.IndexOf(System.String) method is used to get the position of the equals character in the string.. The call to the M:System.String.Substring(System.Int32,System.Int32) method extracts the key name., which starts from the first character in the string and extends for the number of characters returned by the call to the M:System.String.IndexOf(System.String) method. The call to the M:System.String.Substring(System.Int32) method then extracts the value assigned to the key. It starts at one character position beyond the equals character and extends to the end of the string.

Plateforme Windows universelle
Disponible depuis 8
.NET Framework
Disponible depuis 1.1
Bibliothèque de classes portable
Pris en charge dans : plateformes .NET portables
Silverlight
Disponible depuis 2.0
Silverlight pour Windows Phone
Disponible depuis 7.0
Windows Phone
Disponible depuis 8.1
Retour au début
Afficher: