一直以为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); }
标签:string,WriteLine,C#,text,System,Split,words,String From: https://www.cnblogs.com/Dongmy/p/18160489