String.Substring Metodo

Definizione

Recupera una sottostringa da questa istanza.

Questo membro è sottoposto a overload. Per informazioni complete su questo membro, tra cui sintassi, utilizzo ed esempi, fare clic su un nome nell'elenco di overload.

Overload

Nome Descrizione
Substring(Int32)

Recupera una sottostringa da questa istanza. La sottostringa inizia in corrispondenza di una posizione di carattere specificata e continua fino alla fine della stringa.

Substring(Int32, Int32)

Recupera una sottostringa da questa istanza. La sottostringa inizia in corrispondenza di una posizione di carattere specificata e ha una lunghezza specificata.

Substring(Int32)

Recupera una sottostringa da questa istanza. La sottostringa inizia in corrispondenza di una posizione di carattere specificata e continua fino alla fine della stringa.

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

Parametri

startIndex
Int32

Posizione del carattere iniziale in base zero di una sottostringa in questa istanza.

Valori restituiti

Stringa equivalente alla sottostringa che inizia startIndex in questa istanza o Empty se startIndex è uguale alla lunghezza dell'istanza.

Eccezioni

startIndex è minore di zero o maggiore della lunghezza di questa istanza.

Esempio

Nell'esempio seguente viene illustrata l'acquisizione di una sottostringa da una stringa.

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

Nell'esempio seguente viene utilizzato il Substring metodo per separare coppie chiave/valore delimitate da un carattere uguale (=).

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'

Il IndexOf metodo viene usato per ottenere la posizione del carattere uguale nella stringa. La chiamata al Substring(Int32, Int32) metodo estrae il nome della chiave, che inizia dal primo carattere nella stringa ed estende per il numero di caratteri restituiti dalla chiamata al IndexOf metodo . La chiamata al Substring(Int32) metodo estrae quindi il valore assegnato alla chiave. Inizia in corrispondenza di una posizione di carattere oltre il carattere uguale e si estende alla fine della stringa.

Commenti

Chiamare il Substring(Int32) metodo per estrarre una sottostringa da una stringa che inizia in corrispondenza di una posizione di carattere specificata e termina alla fine della stringa. La posizione del carattere iniziale è in base zero; in altre parole, il primo carattere nella stringa è in corrispondenza dell'indice 0, non dell'indice 1. Per estrarre una sottostringa che inizia in corrispondenza di una posizione di carattere specificata e termina prima della fine della stringa, chiamare il Substring(Int32, Int32) metodo .

Note

Questo metodo non modifica il valore dell'istanza corrente. Restituisce invece una nuova stringa che inizia in corrispondenza della startIndex posizione nella stringa corrente.

Per estrarre una sottostringa che inizia con un carattere o una sequenza di caratteri specifica, chiamare un metodo come IndexOf o IndexOf per ottenere il valore di startIndex. Il secondo esempio illustra questo aspetto; estrae un valore chiave che inizia una posizione di carattere dopo il = carattere.

Se startIndex è uguale a zero, il metodo restituisce la stringa originale invariata.

Vedi anche

Si applica a

Substring(Int32, Int32)

Recupera una sottostringa da questa istanza. La sottostringa inizia in corrispondenza di una posizione di carattere specificata e ha una lunghezza specificata.

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

Parametri

startIndex
Int32

Posizione del carattere iniziale in base zero di una sottostringa in questa istanza.

length
Int32

Numero di caratteri nella sottostringa.

Valori restituiti

Stringa equivalente alla sottostringa di lunghezza length che inizia startIndex in questa istanza oppure Empty se startIndex è uguale alla lunghezza dell'istanza e length è zero.

Eccezioni

startIndex più length indica una posizione non all'interno di questa istanza.

oppure

startIndex o length è minore di zero.

Esempio

Nell'esempio seguente viene illustrata una semplice chiamata al Substring(Int32, Int32) metodo che estrae due caratteri da una stringa a partire dalla sesta posizione del carattere, ovvero in corrispondenza dell'indice cinque.

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

Nell'esempio seguente viene usato il Substring(Int32, Int32) metodo nei tre casi seguenti per isolare le sottostringhe all'interno di una stringa. In due casi le sottostringhe vengono usate nei confronti e nel terzo caso viene generata un'eccezione perché vengono specificati parametri non validi.

  • Estrae il singolo carattere alla terza posizione nella stringa (in corrispondenza dell'indice 2) e lo confronta con un "c". Questo confronto restituisce true.

  • Estrae zero caratteri a partire dalla quarta posizione nella stringa (in corrispondenza dell'indice 3) e lo passa al IsNullOrEmpty metodo . Restituisce true perché la chiamata al Substring metodo restituisce String.Empty.

  • Tenta di estrarre un carattere a partire dalla quarta posizione nella stringa. Poiché non esiste alcun carattere in tale posizione, la chiamata al metodo genera un'eccezione ArgumentOutOfRangeException .

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

Nell'esempio seguente viene utilizzato il Substring metodo per separare coppie chiave/valore delimitate da un carattere uguale (=).

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'

Il IndexOf metodo viene usato per ottenere la posizione del carattere uguale nella stringa. La chiamata al Substring(Int32, Int32) metodo estrae il nome della chiave, che inizia dal primo carattere nella stringa ed estende per il numero di caratteri restituiti dalla chiamata al IndexOf metodo . La chiamata al Substring(Int32) metodo estrae quindi il valore assegnato alla chiave. Inizia in corrispondenza di una posizione di carattere oltre il carattere uguale e si estende alla fine della stringa.

Commenti

Chiamare il Substring(Int32, Int32) metodo per estrarre una sottostringa da una stringa che inizia in corrispondenza di una posizione di carattere specificata e termina prima della fine della stringa. La posizione del carattere iniziale è in base zero; in altre parole, il primo carattere nella stringa è in corrispondenza dell'indice 0, non dell'indice 1. Per estrarre una sottostringa che inizia in corrispondenza di una posizione di carattere specificata e continua fino alla fine della stringa, chiamare il Substring(Int32) metodo .

Note

Questo metodo non modifica il valore dell'istanza corrente. Restituisce invece una nuova stringa con length caratteri che iniziano dalla startIndex posizione nella stringa corrente.

Il length parametro rappresenta il numero totale di caratteri da estrarre dall'istanza di stringa corrente. Questo include il carattere iniziale trovato in corrispondenza dell'indice startIndex. In altre parole, il Substring metodo tenta di estrarre caratteri dall'indice all'indice + startIndexstartIndexlength - 1.

Per estrarre una sottostringa che inizia con un carattere o una sequenza di caratteri specifica, chiamare un metodo come IndexOf o LastIndexOf per ottenere il valore di startIndex.

Se la sottostringa deve estendersi da startIndex a una sequenza di caratteri specificata, è possibile chiamare un metodo come IndexOf o LastIndexOf per ottenere l'indice del carattere finale o della sequenza di caratteri. È quindi possibile convertire tale valore in una posizione di indice nella stringa come indicato di seguito:

  • Se è stato cercato un singolo carattere che contrassegna la fine della sottostringa, il length parametro è uguale a - startIndexendIndex+ 1, dove endIndex è il valore restituito del IndexOf metodo o .LastIndexOf Nell'esempio seguente viene estratto un blocco continuo di caratteri "b" da una stringa.

    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
    
  • Se sono stati cercati più caratteri che contrassegnano la fine della sottostringa, il length parametro è uguale - + startIndexendIndexendMatchLength a , dove endIndex è il valore restituito del IndexOf metodo o LastIndexOf e endMatchLength corrisponde alla lunghezza della sequenza di caratteri che contrassegna la fine della sottostringa. Nell'esempio seguente viene estratto un blocco di testo contenente un elemento 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>
    
  • Se la sequenza di caratteri o caratteri non è inclusa alla fine della sottostringa, il length parametro è uguale endIndex - startIndexa , dove endIndex è il valore restituito del IndexOf metodo o .LastIndexOf

Se startIndex è uguale a zero ed length è uguale alla lunghezza della stringa corrente, il metodo restituisce la stringa originale invariata.

Vedi anche

Si applica a