String.Substring 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
从此实例检索子字符串。
重载此成员。 有关此成员的完整信息(包括语法、用法和示例),请单击重载列表中的相应名称。
重载
Substring(Int32) |
从此实例检索子字符串。 子字符串在指定的字符位置开始并一直到该字符串的末尾。 |
Substring(Int32, Int32) |
从此实例检索子字符串。 子字符串从指定的字符位置开始且具有指定的长度。 |
Substring(Int32)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
从此实例检索子字符串。 子字符串在指定的字符位置开始并一直到该字符串的末尾。
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
小于零或大于此实例的长度。
示例
下面的示例演示如何从字符串获取子字符串。
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
以下示例使用 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
当前字符串中的位置开始。
若要提取以特定字符或字符序列开头的子字符串,请调用 或 等IndexOfIndexOf方法来获取 的值startIndex
。 第二个示例说明了这一点:它提取一个键值,该值从字符之后 =
的一个字符位置开始。
如果 startIndex
等于零,则该方法返回原始字符串不变。
另请参阅
- Int32
- Concat(Object)
- Insert(Int32, String)
- Join(String, String[])
- Remove(Int32, Int32)
- Replace(Char, Char)
- Split(Char[])
- Trim(Char[])
适用于
Substring(Int32, Int32)
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
- Source:
- String.Manipulation.cs
从此实例检索子字符串。 子字符串从指定的字符位置开始且具有指定的长度。
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
处开头、长度为 startIndex
的子字符串等效的一个字符串;如果 Empty 等于此实例的长度且 startIndex
为零,则为 length
。
例外
示例
以下示例演示了对 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,因为对 方法的SubstringString.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 方法尝试将字符从索引 startIndex
提取到索引 startIndex
+ length
- 1。
若要提取以特定字符或字符序列开头的子字符串,请调用 或 等IndexOfLastIndexOf方法来获取 的值startIndex
。
如果子字符串应从 startIndex
扩展到指定的字符序列,则可以调用 或 等IndexOfLastIndexOf方法来获取结束字符或字符序列的索引。 然后,可以将该值转换为字符串中的索引位置,如下所示:
如果已搜索要标记子字符串末尾的单个字符,则
length
参数等于 -startIndex
endIndex
+ 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) = 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
如果已搜索要标记子字符串末尾的多个字符,则
length
参数等于 -endMatchLength
+endIndex
startIndex
,其中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
参数等于endIndex
startIndex
- ,其中endIndex
是 或 LastIndexOf 方法的IndexOf返回值。
如果 startIndex
等于零且 length
等于当前字符串的长度,则该方法返回原始字符串不变。