Delete last row from row

I have a line that might look like this:

line1
line2
line3
line4

and I want to delete the last line (line4). How can I do it?

I tried something like this, but it requires me to know how many characters the last line contains:

output = output.Remove(output.Length - 1, 1)
+4
source share
6 answers

Another option:

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

When the last line is empty or contains only a space, and you need to continue deleting the lines until a line other than white is deleted, you must first trim the end of the line before calling LastIndexOf

str = str.Remove(str.TrimEnd().LastIndexOf(Environment.NewLine));
+9
source

If your string is defined as:

string str = @"line1
                line2
                line3
                line4";

Then you can do:

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

If your line has a start / end space or line break, you can do:

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

, , , String.Join .

string[] lines = str.Split(new []{Environment.NewLine}, StringSplitOptions.None);
str = string.Join(Environment.NewLine, lines.Take(lines.Length - 1));
+4
string[] x = yourString.Split('\n');
string result = string.Join(x.Take(x.Length - 1), Enviroment.NewLine);
+2

:

theString = theString.Substring(0, theString.LastIndexOf(Environment.NewLine));
+2
var newStr = str.Substring(0, str.LastIndexOf(Environment.NewLine));
+1
source

All Articles