C# 字符串 - Split() 方法
C# 字符串 Split() 方法根据指定的分隔符将字符串拆分或分离为子字符串,并返回包含此字符串实例子字符串的字符串数组。
需要注意的是,此方法可以通过传递不同的参数进行重载。在下面的示例中,我们可以使用重载的 Split() 方法。
语法
以下是 C# 字符串 Split(Char) 方法的语法 -
public string[] Split(params char[] separation);
参数
此方法接受分隔符作为参数。分隔符可以是分隔子字符串的字符或字符数组(或字符串)。如果分隔符为 null 或空,则该方法将使用空格作为默认分隔符 -
返回值
此方法返回一个包含此实例子字符串的字符串数组。
示例 1
以下代码使用 Split() 方法将一个常用短语拆分为每个单词的字符串数组 -
using System; public class Program { public static void Main(string[] args) { string phrase = "This is tutorialspoint India"; string[] words = phrase.Split(' '); foreach (var word in words) { System.Console.WriteLine($"<{word}>"); } } }
输出
以下是输出 -
<This> <is> <tutorialspoint> <India>
示例 2:按单个字符拆分
我们来看另一个示例,这里我们使用 Split(params char[] separator) 方法的默认语法,以逗号 (,) 分隔字符串 -
using System; public class Program { public static void Main(string[] args) { string fruits = "Apple,Banana,Cherry,Guava"; string[] words = fruits.Split(','); foreach (var word in words) { Console.WriteLine(word); } } }
输出
以下是输出 -
Apple Banana Cherry Guava
示例 3:按多个字符拆分
在此示例中,我们使用 Split(string[] 分隔符, StringSplitOptions 选项) 方法拆分具有多个分隔符的字符 -
using System; class Program { public static void Main() { string fruits = "apple;banana,cherry;Guava"; string[] result = fruits.Split(new char[] {';', ','}); foreach(var word in result) { Console.WriteLine(word); } } }
输出
以下是输出 -
apple banana cherry Guava
示例 4:对子字符串进行限制的拆分
在此示例中,我们使用 Split(char[] separator, int count) 方法将字符串拆分为子字符串,并对子字符串进行限制 -
using System; class Program { public static void Main() { string text = "apple,banana,cherry"; string[] result = text.Split(new char[] { ',' }, 2); foreach (var word in result) { Console.WriteLine(word); } } }
输出
以下是输出 -
apple banana,cherry