String.Split分隔字符串

2022-10-09,,,

一种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);
}

 

《String.Split分隔字符串.doc》

下载本文的Word格式文档,以方便收藏与打印。