String.Substring 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
从此实例检索子字符串。
此成员重载。 有关此成员的完整信息,包括语法、用法和示例,请单击重载列表中的名称。
重载
| 名称 | 说明 |
|---|---|
| Substring(Int32) |
从此实例检索子字符串。 子字符串从指定的字符位置开始,并继续到字符串的末尾。 |
| Substring(Int32, Int32) |
从此实例检索子字符串。 子字符串从指定的字符位置开始,并具有指定的长度。 |
Substring(Int32)
从此实例检索子字符串。 子字符串从指定的字符位置开始,并继续到字符串的末尾。
public:
System::String ^ Substring(int startIndex);
public string Substring(int startIndex);
member this.Substring : int -> string
Public Function Substring (startIndex As Integer) As String
参数
- startIndex
- Int32
此实例中子字符串的起始字符位置从零开始。
返回
与在此实例中开始 startIndex 的子字符串等效的字符串,或者 Empty 如果 startIndex 等于此实例的长度。
例外
startIndex 小于零或大于此实例的长度。
示例
以下示例演示如何从字符串获取子字符串。
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
以下示例使用 Substring 该方法分隔由相等字符=分隔的键/值对。
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'
该方法 IndexOf 用于获取字符串中相等字符的位置。 对方法的调用 Substring(Int32, Int32) 提取键名称,该名称从字符串中的第一个字符开始,并扩展了调用 IndexOf 方法返回的字符数。 然后,对 Substring(Int32) 方法的调用将提取分配给键的值。 它从等于字符之外的一个字符位置开始,并扩展到字符串的末尾。
注解
调用 Substring(Int32) 该方法从字符串中提取子字符串,该字符串从指定字符位置开始,并在字符串末尾结束。 起始字符位置从零开始;换句话说,字符串中的第一个字符位于索引 0,而不是索引 1。 若要提取从指定字符位置开始并在字符串末尾结束的子字符串,请调用 Substring(Int32, Int32) 该方法。
注释
此方法不会修改当前实例的值。 而是返回从当前字符串中的位置开始 startIndex 的新字符串。
若要提取以特定字符或字符序列开头的子字符串,请调用方法,例如 IndexOf 或 IndexOf 获取其值 startIndex。 第二个示例说明了这一点:它提取一个键值,该值在字符之后 = 开始一个字符的位置。
如果 startIndex 等于零,该方法将返回原始字符串不变。
另请参阅
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Split(Char[])
- Trim(Char[])
适用于
Substring(Int32, Int32)
从此实例检索子字符串。 子字符串从指定的字符位置开始,并具有指定的长度。
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
参数
- startIndex
- Int32
此实例中子字符串的起始字符位置从零开始。
- length
- Int32
子字符串中的字符数。
返回
与在此实例中开始的长度length的子字符串等效的字符串,或者Empty如果startIndex等于此实例的长度,则length为startIndex零。
例外
示例
以下示例演示了从第六个字符位置(即索引 5 处)开始从字符串中提取两个字符的方法的简单调用 Substring(Int32, Int32) 。
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
以下示例使用以下 Substring(Int32, Int32) 三种情况下的方法隔离字符串中的子字符串。 在两种情况下,子字符串用于比较,第三种情况下会引发异常,因为指定了无效参数。
它将提取字符串(索引 2)中第三位置的单个字符,并将其与“c”进行比较。 此比较返回
true。它提取从字符串(索引 3 处)第四个位置开始的零个字符,并将其 IsNullOrEmpty 传递给该方法。 这返回 true,因为对方法的 Substring 调用返回 String.Empty。
它尝试从字符串中的第四个位置开始提取一个字符。 由于该位置没有字符,因此该方法调用将引发异常 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
以下示例使用 Substring 该方法分隔由相等字符=分隔的键/值对。
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'
该方法 IndexOf 用于获取字符串中相等字符的位置。 对方法的调用 Substring(Int32, Int32) 提取键名称,该名称从字符串中的第一个字符开始,并扩展了调用 IndexOf 方法返回的字符数。 然后,对 Substring(Int32) 方法的调用将提取分配给键的值。 它从等于字符之外的一个字符位置开始,并扩展到字符串的末尾。
注解
调用 Substring(Int32, Int32) 该方法从字符串中提取子字符串,该字符串从指定字符位置开始,并在字符串末尾之前结束。 起始字符位置从零开始;换句话说,字符串中的第一个字符位于索引 0,而不是索引 1。 若要提取从指定字符位置开始的子字符串,并继续到字符串的末尾,请调用该方法 Substring(Int32) 。
注释
此方法不会修改当前实例的值。 而是返回一个新字符串,其中包含 length 从当前字符串中的位置开始 startIndex 的字符。
该 length 参数表示要从当前字符串实例中提取的字符总数。 这包括索引处 startIndex找到的起始字符。 换句话说,该方法Substring尝试从索引提取字符到索引 + startIndexstartIndexlength - 1。
若要提取以特定字符或字符序列开头的子字符串,请调用方法,例如 IndexOf 或 LastIndexOf 获取其值 startIndex。
如果子字符串应从 startIndex 指定的字符序列扩展,则可以调用方法,例如 IndexOf 或 LastIndexOf 获取结束字符或字符序列的索引。 然后,可以将该值转换为字符串中的索引位置,如下所示:
如果已搜索要标记子字符串末尾的单个字符,则
length参数等于 -startIndexendIndex+ 1,其中endIndex返回或LastIndexOf方法的IndexOf返回值。 以下示例从字符串中提取连续的“b”字符块。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) = bbb如果搜索了要标记子字符串末尾的多个字符,则
length参数等于 -endMatchLength+endIndexstartIndex,其中endIndex返回或LastIndexOf方法的返回值IndexOf,并且endMatchLength是标记子字符串末尾的字符序列的长度。 以下示例提取包含 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>如果子字符串末尾不包含字符或字符序列,则
length参数等于endIndexstartIndex- ,其中endIndex返回或LastIndexOf方法的IndexOf返回值。
如果 startIndex 等于零且 length 等于当前字符串的长度,该方法将返回原始字符串不变。