Fastest way to strip NewLine from string (.Net 2, VS 2005)

  • Thread starter Thread starter jwgoerlich
  • Start date Start date
J

jwgoerlich

Hello group,

What is the fastest way to remove line feeds from the end of a string?
RegEx was too slow. I am using a for loop (code below), but that seems
too cumbersome.

Any suggestions appreciated.

J Wolfgang Goerlich


string logText = txtOutput.Text;
string s10 = Convert.ToChar(10).ToString();
string s13 = Convert.ToChar(13).ToString();

for (int i = logText.Length - 1; i > 0; i--)
{
string s = logText.Substring(i, 1);
if (s == s10 | s == s13)
{
logText = logText.Remove(i);
i--;
}
else
{
break;
}
}

txtOutput.Text = logText;
 
Hello group,

What is the fastest way to remove line feeds from the end of a string?
RegEx was too slow. I am using a for loop (code below), but that seems
too cumbersome.

Any suggestions appreciated.

J Wolfgang Goerlich

String.TrimEnd() ?
 
Ha! Yes, much better. Whew.

logText = logText.TrimEnd(Environment.NewLine.ToCharArray());

Thank you.

J Wolfgang Goerlich
 
Ha! Yes, much better. Whew.

logText = logText.TrimEnd(Environment.NewLine.ToCharArray());

Thank you.

J Wolfgang Goerlich

Well, your code can be made a bit less cumbersome also.

Here's a simplified version of your code:

for (int i = logText.Length - 1; i > 0; i--) {
char s = logText;
if (s == '\n' | s == '\r') {
logText = logText.Remove(i);
} else {
break;
}
}

Now, let's optimise it by only doing the remove once:

int i = logText.Length;
while (i > 0 && ((char s = logText[i-1]) == '\r' || s == '\n') i--;
if (i < logText.Length) logText = logText.Remove(i);

Just a small detour into the land of optimising.
:)
 
Göran Andersson said:
Now, let's optimise it by only doing the remove once:

int i = logText.Length;
while (i > 0 && ((char s = logText[i-1]) == '\r' || s == '\n') i--;
if (i < logText.Length) logText = logText.Remove(i);

Just a small detour into the land of optimising.

What about a detour into a compiler ?

Arne
 
Arne said:
Göran Andersson said:
Now, let's optimise it by only doing the remove once:

int i = logText.Length;
while (i > 0 && ((char s = logText[i-1]) == '\r' || s == '\n') i--;
if (i < logText.Length) logText = logText.Remove(i);

Just a small detour into the land of optimising.

What about a detour into a compiler ?

Arne

Interresting question. The principle of the code works, there is just
two small mistakes in it.

I think that you should be able to spot them yourself. :)
 
Back
Top