欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

String.Split分隔字符串

程序员文章站 2022-04-27 18:29:58
一种char分隔符 string phrase = "The quick brown fox jumps over the lazy dog."; string[] words = phrase.Split(' '); foreach (var word in words) { System.Con ......

一种char分隔符

string phrase = "the quick brown fox jumps over the lazy dog.";
string[] words = phrase.split(' ');
foreach (var word in words)
{
    system.console.writeline($"<{word}>");
}

 

分隔之后的结果,去掉多余的空格

// stringsplitoptions.removeemptyentries移除多余的空格
string phrase = "the quick brown    fox     jumps over the lazy dog.";
string[] words = phrase.split(new char[] { ' ' }, stringsplitoptions.removeemptyentries);
foreach (var word in words)
{
    system.console.writeline($"<{word}>");
}

 

多种char分隔符

// 使用多个分隔符
char[] delimiterchars = { ' ', ',', '.', ':', '\t' };
string text = "one\ttwo three:four,five six seven";
system.console.writeline($"original text: '{text}'");
// public string[] split(params char[] separator);
string[] words = text.split(delimiterchars);
system.console.writeline($"{words.length} words in text:");
foreach (var word in words)
{
    system.console.writeline($"<{word}>");
}

 

多种string分隔符

string[] separatingstrings = { "<<", "..." };
string text = "one<<two......three<four";
system.console.writeline($"original text: '{text}'");
//public string[] split(string[] separator, stringsplitoptions options);
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);
}