String.Substring Metodo

Definizione

Recupera una sottostringa da questa istanza.

Si tratta di un membro di overload. Per informazioni complete su questo membro, inclusi la sintassi, l'uso e gli esempi, fare clic su un nome nell'elenco degli overload.

Overload

Substring(Int32)

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

Substring(Int32, Int32)

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

Substring(Int32)

Recupera una sottostringa da questa istanza. La sottostringa inizia in corrispondenza di un carattere specificato 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 iniziale in base zero del carattere di una sottostringa in questa istanza.

Restituisce

Stringa equivalente alla sottostringa che inizia in corrispondenza di startIndex in questa istanza oppure Empty se startIndex è uguale alla lunghezza di questa 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.

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

Nell'esempio seguente viene usato 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 della 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 a una posizione di carattere oltre il carattere uguale e si estende alla fine della stringa.

Commenti

Si chiama il Substring(Int32) metodo per estrarre una sottostringa da una stringa che inizia a una posizione di carattere specificata e termina alla fine della stringa. La posizione del carattere iniziale è basata su zero; in altre parole, il primo carattere della stringa è all'indice 0, non all'indice 1. Per estrarre una sottostringa che inizia in una posizione di carattere specificata e termina prima della fine della stringa, chiamare il Substring(Int32, Int32) metodo.

Nota

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

Per estrarre una sottostringa che inizia con una determinata sequenza di caratteri o caratteri, chiamare un metodo come IndexOf o IndexOf per ottenere il valore di startIndex. Il secondo esempio illustra questo; 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 della posizione del carattere specificata e ha la 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 iniziale in base zero del carattere di una sottostringa in questa istanza.

length
Int32

Numero di caratteri nella sottostringa.

Restituisce

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

Eccezioni

La somma di startIndex e length indica una posizione non all'interno di questa istanza.

-oppure-

startIndex o length è minore di zero.

Esempio

Nell'esempio Substring(Int32, Int32) seguente viene illustrata una semplice chiamata al 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 sottostringa all'interno di una stringa. In due casi vengono usate le sottostringa nei confronti e, nel terzo caso, viene generata un'eccezione perché vengono specificati parametri non validi.

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

  • Estrae zero caratteri a partire dalla quarta posizione della 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 usato 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 della 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 a una posizione di carattere oltre il carattere uguale e si estende alla fine della stringa.

Commenti

Si chiama il Substring(Int32, Int32) metodo per estrarre una sottostringa da una stringa che inizia a una posizione di carattere specificata e termina prima della fine della stringa. La posizione del carattere iniziale è basata su zero; in altre parole, il primo carattere della stringa è all'indice 0, non all'indice 1. Per estrarre una sottostringa che inizia in una posizione di carattere specificata e continua alla fine della stringa, chiamare il Substring(Int32) metodo .

Nota

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

Il length parametro rappresenta il numero totale di caratteri da estrarre dall'istanza di stringa corrente. Include il carattere iniziale trovato nell'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 una determinata sequenza di caratteri o caratteri, chiamare un metodo come IndexOf o LastIndexOf per ottenere il valore di startIndex.

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

  • Se si è cercato un singolo carattere che contrassegna la fine della sottostringa, il length parametro è uguale endIndexstartIndex - a + 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 si è cercato più caratteri che contrassegnano la fine della sottostringa, il length parametro è uguale - + startIndexendIndexendMatchLength a , dove endIndex è il valore restituito del IndexOf metodo o LastIndexOf ed endMatchLength è la 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 nella 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