如何拆分字符串并保留分隔符?

use*_*312 3 c# asp.net string split translation

我知道你看到很多像我这样的问题,但我希望我的有点不同.我正在翻译,我想将文本分成句子,但是当我编写这段代码时:

public static string[] GetSentences(string Text)
{
    if (Text.Contains(". ") || Text.Contains("? ") || Text.Contains("! "))
        return Text.Split(new string[] { ". ", "? ", "! " }, StringSplitOptions.RemoveEmptyEntries);
    else
        return new string[0];
}
Run Code Online (Sandbox Code Playgroud)

它删除了".","?","!".我想保留他们我怎么能这样做.


注意:我想用"."点和空格分隔,"?"问号和空格......

Hen*_*man 16

很简单,先替换它们.我会使用它"|"的可读性,但你可能想要使用更具异国情调的东西.

// this part could be made a little smarter and more flexible.    
// So, just the basic idea:
Text = Text.Replace(". ", ". |").Replace("? ", "? |").Replace("! ", "! |");

if (Text.Contains("|")) 
    return Text.Split('|', StringSplitOptions.RemoveEmptyEntries);
Run Code Online (Sandbox Code Playgroud)

我想知道else return new string[0];,这看起来很奇怪.假设当没有分隔符时你希望返回输入字符串,你应该删除if/else构造.