跳到主要内容

C# String Substring() 字符串子串方法

Substring() 方法从给定字符串返回一个子字符串。

示例

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string text = "C# is fun";

// 从索引 6 返回长度为 3 的子字符串 Console.WriteLine(text.Substring(6, 3)); Console.ReadLine(); } } } // 输出: fun

Substring() 语法

字符串 Substring() 方法的语法如下:

Substring(int startIndex, int length)

在这里,Substring()String 类的一个方法。

Substring() 参数

Substring() 方法接受以下参数:

  • startIndex - 子字符串的开始索引
  • length - (可选) - 子字符串的长度

Substring() 返回值

Substring() 方法从给定字符串返回一个子字符串。

示例 1: C# Substring() 无长度

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string text = "Programiz";


// 返回从第二个字符开始的子字符串 string result = text.Substring(1); Console.WriteLine(result); Console.ReadLine(); } } }

输出

rogramiz

注意上面示例中的这行代码:

string result = text.Substring(1);

代码 text.Substring(1) 返回从 "Programiz" 的第二个字符开始的子字符串。

示例 2: C# Substring() 带长度

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string text = "Programiz is for programmers";


// 从第一个字符开始返回长度为 9 的子字符串 string result = text.Substring(0, 9); Console.WriteLine(result); Console.ReadLine(); } } }

输出

Programiz

注意上面示例中的这行代码:

string result = text.Substring(0, 9);

在这里,

  • 0text 的第一个字符)是子字符串的开始索引
  • 9 是子字符串的长度

这给我们带来了子字符串 "Programiz"

示例 3: C# Substring() 在特定字符之前

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string text = "C#. Programiz";


// 返回从索引 0 到 '.' 之前的索引的子字符串 string result = text.Substring(0, text.IndexOf('.')); Console.WriteLine(result); Console.ReadLine(); } } }

输出

C#

在这里,text.IndexOf('.') 给出了子字符串的长度,即 '.' 的索引。