Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete the first n lines in a string in C#?

Tags:

string

c#

.net

How can I delete the first n lines in a string?

Example:

String str = @"a
b
c
d
e";

String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
like image 521
Gjorgji Avatar asked Feb 09 '11 00:02

Gjorgji


4 Answers

You can use LINQ:

String str = @"a
b
c
d
e";

int n = 2;
string[] lines = str
    .Split(Environment.NewLine.ToCharArray())
    .Skip(n)
    .ToArray();

string output = string.Join(Environment.NewLine, lines);

// Output is 
// "c
// d
// e"
like image 144
Omar Avatar answered Nov 18 '22 03:11

Omar


If you need to take into account "\r\n" and "\r" and "\n" it's better to use the following regex:

public static class StringExtensions
{
    public static string RemoveFirstLines(string text, int linesCount)
    {
        var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount);
        return string.Join(Environment.NewLine, lines.ToArray());
    }
}

Here are some more details about splitting text into lines.

like image 35
username Avatar answered Nov 18 '22 03:11

username


Combination of Get the index of the nth occurrence of a string? (search for Environment.NewLine) and substring should do the trick.

like image 3
Lukáš Novotný Avatar answered Nov 18 '22 03:11

Lukáš Novotný


Try the following:

public static string DeleteLines(string s, int linesToRemove)
{
    return s.Split(Environment.NewLine.ToCharArray(), 
                   linesToRemove + 1
        ).Skip(linesToRemove)
        .FirstOrDefault();
}

the next example:

string str = @"a
b
c
d
e";
string output = DeleteLines(str, 2);

returns

c
d
e
like image 3
Oleks Avatar answered Nov 18 '22 03:11

Oleks