简体   繁体   中英

Split a string by a newline in C#

I have a string like this :

SITE IÇINDE OLMASI\\nLÜKS INSAA EDILMIS OLMASI\\nSITE IÇINDE YÜZME HAVUZU, VB. SOSYAL YASAM ALANLARININ OLMASI.\\nPROJESİNE UYGUN YAPILMIŞ OLMASI

I'm trying to split and save this string like this :

array2 = mystring.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

foreach (var str in sarray2)
{
    if (str != null && str != "")
    {
        _is.RelatedLook.InternalPositive += str;
    }
}

I also tried

Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);

This obviously doesn't split my string. How can I split my string in a correct way? Thanks

var result = mystring.Split(new string[] {"\\n"}, StringSplitOptions.None);

由于新行粘在您的案例中的单词上,因此您必须使用额外的反斜杠。

In linqpad I was able to get it split

var ug = "SITE IÇINDE OLMASI\nLÜKS INSAA EDILMIS OLMASI\nSITE IÇINDE YÜZME HAVUZU, VB. SOSYAL YASAM ALANLARININ OLMASI.\nPROJESİNE UYGUN YAPILMIŞ OLMASI";
var test = ug.Split('\n');
test.Dump();

在此处输入图片说明

Convert the Literal character sequence for a new line to a string, and split by that - ie

string clipboardText = Clipboard.GetText();
        string[] seperatingTags = { Environment.NewLine.ToString() };
        List<string> Lines = clipboardText.Split(seperatingTags, StringSplitOptions.RemoveEmptyEntries).ToList();

Split by a new line is very tricky since it is not consistent and you can have multiple lines or different combinations of splitting characters. I have tried many methods including some in this thread, but finally, I came up with a solution of my own which seems to fix all the cases I came across.

I am using Regex.Split with some cleaning as follows (I have wrapped it in extension method)

public static IEnumerable<string> SplitByLine(this string str)
{
    return Regex
        .Split(str, @"((\r)+)?(\n)+((\r)+)?")
        .Select(i => i.Trim())
        .Where(i => !string.IsNullOrEmpty(i));
}

usage

var lines = "string with\nnew lines\r\n\n\n with all kind of weird com\n\r\r\rbinations".SplitByLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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