繁体   English   中英

如何通过换行符分割字符串,而不是连续丢失多个换行符?

[英]How to split a string by line breaks and not lose multiple line breaks in a row?

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

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

然后,我遍历拆分数组进行渲染。 因此,如果我的字符串是:

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

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

删除StringSplitOptions.RemoveEmptyEntries并删除一些条目,然后离开:

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

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

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

第二个避免StringSplitOptions.RemoveEmptyEntries 为了获得所有的换行符,您需要指定StringSplitOptions.None (似乎没有StringSplitOptionsstring[]没有重载)。

然后“手动”过滤。 我在这里看不到聪明的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部分并使用分隔符。

但是然后您实际上得到了“不需要的”示例结果,因为有两个换行符(\\ r \\ n \\ r \\ n => 4个条目),所以有4个空条目。 因此,您可能需要更改为new[]{"\\v", "\\r\\n"} 您的问题中的"\\\\v"是什么?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM