Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 905
lizart Avatar asked Dec 06 '13 19:12

lizart


People also ask

How do I remove the last line of a string in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb.

How do I remove the last line of a string in Python?

Method 2: Use the strip() Function to Remove a Newline Character From the String in Python.

How do I remove the last 3 characters from a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.


1 Answers

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));
like image 100
p.s.w.g Avatar answered Sep 20 '22 06:09

p.s.w.g