FLX
FLX

Reputation: 2679

C# removing last line in string

I'm using C# (unity3d).

I have a string containing lines separated by \r\n, and I need to remove the last line. z I managed to make something work but it takes 3 lines, I feel that maybe there could be something shorter in C# to do that.

Here is my current code :

int index = infoTxt.text.LastIndexOf("\r\n");
infoTxt.text = infoTxt.text.Substring(0, index - 2);
infoTxt.text = infoTxt.text.Substring(0, infoTxt.text.LastIndexOf("\r\n")+2);

Is this efficient enough to be used often, with a text string growing as time goes on ? This is for a console-like system.

Upvotes: 2

Views: 1822

Answers (2)

Gilad Green
Gilad Green

Reputation: 37299

You can achieve this by simply doing:

var trimmed = text.Substring(0, text.LastIndexOf("\r\n"));

Tested with:

var text = File.ReadAllText("data.txt"); // "row1\r\nrow2\r\nrow3"
var trimmed = text.Substring(0, text.LastIndexOf("\r\n")); // "row1\r\nrow2"

Your double sub-stringing suggests your data ends with an empty line. If so then you need the second last index of it:

string value = "\r\n";
var text = File.ReadAllText("data.txt"); //"row1\r\nrow2\r\nrow3\r\n"
int lastPosition = text.LastIndexOf(value);
var trimmed = text.Substring(0, text.LastIndexOf(value, lastPosition-1)); // "row1\r\nrow2"

Last - see @serge.karalenka suggestion to use Environment.NewLine instead of "\r\n"


If you have and option of no new lines then you should:

var trimmed = text.Substring(0, lastPosition == -1 ? text.Length : 
                  text.LastIndexOf(Environment.NewLine, lastPosition - 1));

Upvotes: 1

serge.karalenka
serge.karalenka

Reputation: 990

You override the results of the 2nd line with your 3rd line (just adding "\r\n" to it).

Also, you can use Environment.NewLine instead of "\r\n", so your code will be cross-platform. So just one line will suffice for your task:

var trimmed = text.Substring(0, text.LastIndexOf(Environment.NewLine));

Upvotes: 0

Related Questions