C# 字符串 - Substring() 方法
C# 字符串 Substring() 方法用于从当前字符串实例中检索子字符串,从指定字符位置开始,直至字符串末尾。如果指定了长度,该方法将返回从该字符位置开始,延伸至指定长度的子字符串。
语法
以下是 C# 字符串 Substring() 方法的语法 -
仅包含 startIndex 的语法 -
public string Substring (int startIndex);
包含 startIndex 和 length 的语法 -
public string Substring(int startIndex, int length);
参数
此方法接受以下参数 -
- startIndex:表示子字符串在当前字符串实例中的起始字符位置。
- length:表示子字符串中要包含的字符数。
返回值
此方法返回一个新字符串,它是当前字符串实例的子字符串,从指定位置开始,并具有指定的长度。
示例 1:从字符串中提取子字符串
以下是 Substring() 方法的一个基本示例,我们提取从指定索引位置开始并在当前实例末尾延续的子字符串 -
using System; class Program { public static void Main() { string text = "Hello, tpians!"; string Substring = text.Substring(3); Console.Write("This is substring: "+ Substring); } }
输出
以下是输出 -
This is substring: lo, tpians!
示例 2:提取指定长度内的子字符串
我们来看另一个示例。这里,我们使用 substring() 方法从给定的起始位置检索到指定长度的子字符串。−
using System; class Program { public static void Main() { string text = "Hello, tpians!"; string Substring = text.Substring(3, 7); Console.Write("This is substring: "+ Substring); } }
输出
以下是输出 -
This is substring: lo, tpi
示例 3:提取前 N 个字符
在本例中,我们使用 Substring() 方法提取前 n 个字符。要提取前 n 个字符,我们需要将 startIndex 设置为 '0',然后设置长度 -
using System; class Program { public static void Main() { string text = "Hello, tutorialspoint"; string Substring = text.Substring(0, 10); Console.Write("First n character: "+ Substring); } }
输出
以下是输出 -
True
示例 4:处理超出范围的情况
以下示例处理超出范围的情况。如果起始索引大于字符串的长度或为"-1",则会收到错误 -
using System; class Program { public static void Main() { string str = "Hi, tutorialspoint"; try { string substring = str.Substring(20); } catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"Error: {ex.Message}"); } } }
输出
以下是输出 -
Error: startIndex cannot be larger than length of string. Parameter name: startIndex