如何用空行拆分字符串?

时间:2015-03-09 13:53:01

标签: c# string

我想用空条目分割我的字符串。我知道你可以用字符串选项删除这些,但在我的情况下我需要它们来分割字符串。谢谢!

string[] text = content.Split(' '); 

例如,你有这个字符串:

Hi my Name is Max.
I'm 24 years old.

I like programming.

在old和I之间拆分字符串。

我的代码:

            WebClient client = new WebClient();
            Stream stream = client.OpenRead("https://gist.githubusercontent.com/Quackmatic/f8deb2b64dd07ea0985d/raw/macbeth.txt");
            StreamReader reader = new StreamReader(stream);
            string[] text = reader.ReadToEnd().Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(text[i]);
            }
            Console.ReadLine();

每个新行都会分割字符串。问题是我想要我的文字的完整段落。

我的输出:

string[0] = ACT I.
string[1] = SCENE I. An open place.
string[2] =[An open place. Thunder and lightning. Enter three Witches.]

我想要什么。

string[0] = ACT I.
string[1] = SCENE I. An open place.
            [An open place. Thunder and lightning. Enter three Witches.]
string[2] = FIRST WITCH.
            When shall we three meet again
            In thunder, lightning, or in rain?

或......

    Doubtful it stood;
    As two spent swimmers that do cling together
    And choke their art. The merciless Macdonwald, 
    Worthy to be a rebel, for to that
    The multiplying villainies of nature
    Do swarm upon him, from the Western isles
    Of kerns and gallowglasses is supplied;
    And fortune, on his damned quarrel smiling,
    Show'd like a rebel's whore. But all's too weak;
    For brave Macbeth, well he deserves that name, 
    Disdaining fortune, with his brandish'd steel,
    Which smok'd with bloody execution,
    Like valour's minion,
    Carv'd out his passage, till he fac'd the slave;
    And ne'er shook hands, nor bade farewell to him,
    Till he unseam'd him from the nave to the chaps,
    And fix'd his head upon our battlements

我以为我可以通过用空行拆分文本来获得结果。

2 个答案:

答案 0 :(得分:1)

var foo = bar.Split(new string[] {Environment.NewLine + Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);

组合Environment.NewLine + Environment.NewLine非常重要,因为这只会在新行后面跟一个新行(又名空白行)时拆分并相应地拆分

结果是:

foo[0] = "Hi my Name is Max.\r\nI'm 24 years old."
foo[1] = "I like programming."

编辑 - 根据您的新输入,试试这个:

var web = new WebClient();
var stream = web.OpenRead("https://gist.githubusercontent.com/Quackmatic/f8deb2b64dd07ea0985d/raw/macbeth.txt");
if (stream == null) return;
var reader = new StreamReader(stream).ReadToEnd();
var io = reader.Split(new string[] { "\n\n" }, StringSplitOptions.RemoveEmptyEntries);

Result

从这里你可以迭代并做你想做的事情(即行[i] .StartsWith(&#34; ACT&#34;)如果你愿意的话把它放到一个对象中)

答案 1 :(得分:-5)

如果您要搜索空行,则应该执行类似

的操作
"value".split(environment.newline+environment.newline)