Substring()
方法返回给定字符串的子字符串。
示例
using System;
namespace CsharpString
{
class Test
{
public static void Main(string[] args)
{
string text = "C# is fun";
// Returns substring of length 3 from index 6
Console.WriteLine(text.Substring(6, 3));
Console.ReadLine();
}
}
}
// Output: 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";
// Returns substring from the second character
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";
// Returns substring of length 9 from the first character
string result = text.Substring(0, 9);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
输出
Programiz
请注意上面示例中的这行代码
string result = text.Substring(0, 9);
这里,
- 0 (text 的第一个字符)是子字符串的起始索引
- 9 是子字符串的长度
这给了我们子字符串 "Programiz"
。
示例 3:C# Substring() 在特定字符之前
using System;
namespace CsharpString
{
class Test
{
public static void Main(string[] args)
{
string text = "C#. Programiz";
// Returns substring from index 0 to index before '.'
string result = text.Substring(0, text.IndexOf('.'));
Console.WriteLine(result);
Console.ReadLine();
}
}
}
输出
C#
这里,text.IndexOf('.')
给出了子字符串的长度,也就是 '.'
的索引。