如何通过换行符拆分字符串而不会丢失一行中的多个换行符?

时间:2015-12-18 12:25:23

标签: c# arrays parsing split line-breaks

我有以下代码用于获取字符串并通过换行符将其分解:

var delimiters = new string[] { "\\v", "\v", "\r", "\n" };
string[] split = textWithStyle.Text.Split(
                     delimiters, 
                     StringSplitOptions.RemoveEmptyEntries);

然后我遍历split数组进行渲染。所以如果我的字符串是:

Today is Monday and the 7th
Tomorrow is Tuesday and the 8th

我得到一个包含2个项目的数组:

[0] Today is Monday and the 7th
[1] Tomorrow is Tuesday and the 8th

我刚刚意识到的问题是,如果字符串在一行中有多个换行符,如:

Today is Monday and the 7th


Tomorrow is Tuesday and the 8th

如果我查看文本编辑器,我会在这里看到多个CRLF,但是我的解析代码没有区分这个用例和单个换行符,而上面的内容仍然只会在数组中创建2个元素线

如何更改我的解析代码,如果我连续有多个换行符,它会将除第一个换行符之外的每个换行符添加到数组中。因此,如果上面的字符串有3个CRLF,那么我希望我的数组是:

[0] Today is Monday and the 7th
[1] empty string
[2] empty string
[3] Tomorrow is Tuesday and the 8th

如果我只是删除了StringSplitOptions.RemoveEmptyEntries,那么我最终会得到

[0] Today is Monday and the 7th
[1] empty string
[2] empty string
[3] empty string
[4] empty string
[5] Tomorrow is Tuesday and the 8th

我不想要(因为它有比我想要的空间条目更多)

2 个答案:

答案 0 :(得分:1)

删除onActivityPaused并删除部分条目,然后离开:

StringSplitOptions.RemoveEmptyEntries

对于结果数组中的每个空条目,这是一个换行符。

答案 1 :(得分:0)

首先,我建议使用Environment.NewLine代替您的构造。通过使用("\\r", "\\n"),您可以获得更多空字符串。

第二个避免StringSplitOptions.RemoveEmptyEntries。要获得所有换行符,您需要指定StringSplitOptions.None(对于string[]而言,如果没有StringSplitOptions,则似乎没有重载。

然后手动过滤""。我不能在这里看到一个聪明的linq单行。

        List<string> resultList = new List<string>();
        bool previousEmpty = false;
        foreach (string split in textWithStyle.Text.Split(new[] {Environment.NewLine, "\v"}, StringSplitOptions.None))
        {
            if (!string.IsNullOrEmpty(split))
                previousEmpty = false;
            else if (!previousEmpty)
            {
                previousEmpty = true;
                continue;
            }               

            resultList.Add(split);
        }

        string[] split = resultList.ToArray();

编辑:如果您想要\ r和\ n的额外条目,我并不完全清楚。您的示例结果表明。如果是,请跳过Environment.NewLine部分并使用您的分隔符。

然而你实际上得到了你的&#34;不想要的&#34;示例结果,因为有4个空条目,因为有两个换行符(\ r \ n \ r \ n \ n =&gt; 4个条目)。因此,您可能希望更改为new[]{"\v", "\r\n"}。你问题中的"\\v"是什么?