lizart
lizart

Reputation: 137

Remove last line from a string

I have a string that could look like this:

line1
line2
line3
line4

and I want to remove the last line (line4). How would I do this?

I attempted something like this but it requies that I know how many characters the last line contains:

output = output.Remove(output.Length - 1, 1)

Upvotes: 7

Views: 22131

Answers (6)

p.s.w.g
p.s.w.g

Reputation: 149040

Another option:

str = str.Remove(str.LastIndexOf(Environment.NewLine));

When the last line is empty or contains only white space, and you need to continue removing lines until a non-white-space line has been removed, you just have to trim the end of the string first before calling LastIndexOf:

str = str.Remove(str.TrimEnd().LastIndexOf(Environment.NewLine));

Upvotes: 20

narendra
narendra

Reputation: 163

var newStr = str.Substring(0, str.LastIndexOf(Environment.NewLine));

Upvotes: 1

Guffa
Guffa

Reputation: 700592

Locate the last line break, and get the part of the string before that:

theString = theString.Substring(0, theString.LastIndexOf(Environment.NewLine));

Upvotes: 4

Tim Schmelter
Tim Schmelter

Reputation: 460228

You can split it, take all but the last line and use String.Join to create the final string.

string[] lines = str.Split(new []{Environment.NewLine}, StringSplitOptions.None);
str = string.Join(Environment.NewLine, lines.Take(lines.Length - 1));

Upvotes: 4

Habib
Habib

Reputation: 223312

If you have your string defined as:

string str = @"line1
                line2
                line3
                line4";

Then you can do:

string newStr = str.Substring(0, str.LastIndexOf(Environment.NewLine));

If your string has starting/ending whitespace or Line break then you can do:

string newStr = str
                   .Substring(0, str.Trim().LastIndexOf(Environment.NewLine));

Upvotes: 4

It'sNotALie.
It'sNotALie.

Reputation: 22804

string[] x = yourString.Split('\n');
string result = string.Join(x.Take(x.Length - 1), Enviroment.NewLine);

Upvotes: 3

Related Questions