System.String.Substring 方法 (Int32, Int32)

方法描述

从此实例检索子字符串。 子字符串从指定的字符位置开始且具有指定的长度。

语法定义(C# System.String.Substring 方法 (Int32, Int32) 的用法)

public string Substring(
	int startIndex,
	int length
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
startIndex System-Int32 此实例中子字符串的起始字符位置(从零开始)。
length System-Int32 子字符串中的字符数。
返回值 System.String 与此实例中在 startIndex 处开头、长度为 length 的子字符串等效的一个字符串,如果 startIndex 等于此实例的长度且 length 为零,则为 Empty。

提示和注释

startIndex 从零开始。

注意

此方法不修改当前实例的值。 而是返回一个新字符串,具有从当前字符串中 startIndex 位置开始的 length 个字符。

System.String.Substring 方法 (Int32, Int32)例子

在两种情况下,在比较中使用子字符串,在第三种情况下,由于指定的参数无效而引发异常。

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);
}

异常

异常 异常描述
ArgumentOutOfRangeException
  • startIndex 加 length 之和指示的位置不在此实例中。
  • startIndex 或 length 小于零。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。