如何在 C# 中使用 String.Split 分隔字符串

一直以为split是用来分隔字符的,没想到还可以分隔数组。让程序变得更简单。微软官网的介绍在此记录下。

https://learn.microsoft.com/zh-cn/dotnet/csharp/how-to/parse-strings-using-split

 

1、分单个字符

string phrase = "The quick brown fox jumps over the lazy dog.";
string[] words = phrase.Split(' ');

foreach (var word in words)
{
    System.Console.WriteLine($"<{word}>");
}

 2、String.Split 可使用多个分隔符。

char[] delimiterChars = { ' ', ',', '.', ':', '\t' };

string text = "one\ttwo three:four,five six seven";
System.Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(delimiterChars);
System.Console.WriteLine($"{words.Length} words in text:");

foreach (var word in words)
{
    System.Console.WriteLine($"<{word}>");
}

  3、String.Split 可采用字符串数组(充当用于分析目标字符串的分隔符的字符序列,而非单个字符)

string[] separatingStrings = { "<<", "..." };

string text = "one<<two......three<four";
System.Console.WriteLine($"Original text: '{text}'");

string[] words = text.Split(separatingStrings, System.StringSplitOptions.RemoveEmptyEntries);
System.Console.WriteLine($"{words.Length} substrings in text:");

foreach (var word in words)
{
    System.Console.WriteLine(word);
}

  

posted @ 2024-04-26 17:13  yinghualeihenmei  阅读(22)  评论(0编辑  收藏  举报