String.Substring Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Recupera uma substring desta instância.
Este membro está sobrecarregado. Para informações completas sobre este membro, incluindo sintaxe, uso e exemplos, clique num nome na lista de sobrecarga.
Sobrecargas
| Name | Description |
|---|---|
| Substring(Int32) |
Recupera uma substring desta instância. A subcadeia começa numa posição especificada de carácter e continua até ao fim da cadeia. |
| Substring(Int32, Int32) |
Recupera uma substring desta instância. A subcadeia começa numa posição de carácter especificada e tem um comprimento especificado. |
Substring(Int32)
Recupera uma substring desta instância. A subcadeia começa numa posição especificada de carácter e continua até ao fim da cadeia.
public:
System::String ^ Substring(int startIndex);
public string Substring(int startIndex);
member this.Substring : int -> string
Public Function Substring (startIndex As Integer) As String
Parâmetros
- startIndex
- Int32
A posição inicial de uma subcadeia neste caso, baseada em zero.
Devoluções
Uma cadeia que é equivalente à subcadeia que começa em startIndex nesta instância, ou Empty se startIndex for igual ao comprimento desta instância.
Exceções
startIndex é menor que zero ou superior ao comprimento desta instância.
Exemplos
O exemplo seguinte demonstra a obtenção de uma substring a partir de uma string.
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
O exemplo seguinte utiliza o Substring método para separar pares chave/valor que são delimitados por um carácter igual (=).
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'
O IndexOf método é usado para obter a posição do carácter igual na cadeia. A chamada ao Substring(Int32, Int32) método extrai o nome da chave, que começa no primeiro carácter da cadeia e estende-se para o número de caracteres devolvidos pela chamada ao IndexOf método. A chamada ao Substring(Int32) método extrai então o valor atribuído à chave. Começa numa posição de carácter acima do caractere igual e estende-se até ao fim da sequência.
Observações
Chama-se o Substring(Int32) método para extrair uma subcadeia de uma cadeia que começa numa posição de carácter especificada e termina no final da cadeia. A posição inicial do carácter é baseada em zero; Ou seja, o primeiro carácter da cadeia está no índice 0, não no índice 1. Para extrair uma subcadeia que começa numa posição de carácter especificada e termina antes do fim da cadeia, chama o Substring(Int32, Int32) método.
Note
Este método não modifica o valor da instância atual. Em vez disso, devolve uma nova corda que começa na startIndex posição da corda atual.
Para extrair uma subcadeia que começa com um carácter particular ou sequência de caracteres, chame um método como IndexOf ou IndexOf para obter o valor de startIndex. O segundo exemplo ilustra isto; extrai um valor-chave que começa uma posição de carácter depois da = personagem.
Se startIndex for igual a zero, o método devolve a cadeia original inalterada.
Ver também
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Split(Char[])
- Trim(Char[])
Aplica-se a
Substring(Int32, Int32)
Recupera uma substring desta instância. A subcadeia começa numa posição de carácter especificada e tem um comprimento especificado.
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
Parâmetros
- startIndex
- Int32
A posição inicial de uma subcadeia neste caso, baseada em zero.
- length
- Int32
O número de caracteres na substring.
Devoluções
Uma cadeia que é equivalente à subcadeia de comprimento length que começa em startIndex nesta instância, ou Empty se startIndex for igual ao comprimento desta instância e length for zero.
Exceções
startIndex Mais length indica uma posição que não está neste caso.
-ou-
startIndex ou length é inferior a zero.
Exemplos
O exemplo seguinte ilustra uma chamada simples ao Substring(Int32, Int32) método que extrai dois caracteres de uma cadeia a partir da sexta posição do carácter (ou seja, no índice cinco).
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
O exemplo seguinte utiliza o Substring(Int32, Int32) método nos três casos seguintes para isolar substrings dentro de uma string. Em dois casos, as subcadeias são usadas em comparações, e no terceiro caso é lançada uma exceção porque parâmetros inválidos são especificados.
Extrai o carácter único na terceira posição da cadeia (no índice 2) e compara-o com um "c". Esta comparação retorna
true.Extrai zero caracteres começando na quarta posição da cadeia (no índice 3) e passa-os ao IsNullOrEmpty método. Isto retorna verdadeiro porque a chamada ao Substring método devolve String.Empty.
Tenta extrair um carácter começando na quarta posição da cadeia. Como não há carácter nessa posição, a chamada de método lança uma ArgumentOutOfRangeException exceção.
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
O exemplo seguinte utiliza o Substring método para separar pares chave/valor que são delimitados por um carácter igual (=).
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'
O IndexOf método é usado para obter a posição do carácter igual na cadeia. A chamada ao Substring(Int32, Int32) método extrai o nome da chave, que começa no primeiro carácter da cadeia e estende-se para o número de caracteres devolvidos pela chamada ao IndexOf método. A chamada ao Substring(Int32) método extrai então o valor atribuído à chave. Começa numa posição de carácter acima do caractere igual e estende-se até ao fim da sequência.
Observações
Chamas o Substring(Int32, Int32) método para extrair uma subcadeia de uma cadeia que começa numa posição de carácter especificada e termina antes do fim da cadeia. A posição inicial do carácter é baseada em zero; Ou seja, o primeiro carácter da cadeia está no índice 0, não no índice 1. Para extrair uma subcadeia que começa numa posição de carácter especificada e continua até ao fim da cadeia, chama o Substring(Int32) método.
Note
Este método não modifica o valor da instância atual. Em vez disso, devolve uma nova cadeia com length caracteres a partir da startIndex posição na cadeia atual.
O length parâmetro representa o número total de caracteres a extrair da instância da cadeia atual. Isto inclui o carácter inicial encontrado no índice startIndex. Por outras palavras, o Substring método tenta extrair caracteres do índice startIndex para o índice startIndex + length - 1.
Para extrair uma subcadeia que começa com um carácter particular ou sequência de caracteres, chame um método como IndexOf ou LastIndexOf para obter o valor de startIndex.
Se a subcadeia se estender de startIndex para uma sequência de caracteres especificada, pode chamar um método como IndexOf ou LastIndexOf para obter o índice do carácter final ou sequência de caracteres. Pode então converter esse valor para uma posição de índice na cadeia da seguinte forma:
Se procuraste um único carácter que marque o fim da substring, o
lengthparâmetro éendIndex-startIndexigual a + 1, ondeendIndexé o valor de retorno do IndexOf método ou.LastIndexOf O exemplo seguinte extrai um bloco contínuo de caracteres "b" de uma cadeia.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) = bbbSe procurou por vários caracteres que devem marcar o fim da substring, o
lengthparâmetro éendMatchLengthendIndexstartIndex- + igual a , ondeendIndexé o valor de retorno do IndexOf método ouLastIndexOf, eendMatchLengthé o comprimento da sequência de caracteres que marca o fim da substring. O exemplo seguinte extrai um bloco de texto que contém um 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 a sequência de caracteres ou caracteres não estiver incluída no final da substring, o
lengthparâmetro éendIndexstartIndex- igual a , ondeendIndexé o valor de retorno do IndexOf método ouLastIndexOf.
Se startIndex for igual a zero e length igual ao comprimento da sequência atual, o método devolve a cadeia original inalterada.