jason
jason

Reputation: 7164

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

Upvotes: 6

Views: 53894

Answers (4)

Gravity API
Gravity API

Reputation: 849

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();

Upvotes: 2

TimP268
TimP268

Reputation: 39

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

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

Upvotes: 3

Kixoka
Kixoka

Reputation: 1161

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();

enter image description here

Upvotes: 3

A.B.
A.B.

Reputation: 2470

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

Since the new line is glued to the words in your case, you have to use an additional back-slash.

Upvotes: 16

Related Questions