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

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;
 
P

PhilipDaniels

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() ?
 
J

jwgoerlich

Ha! Yes, much better. Whew.

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

Thank you.

J Wolfgang Goerlich
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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.
:)
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

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
 
?

=?ISO-8859-1?Q?G=F6ran_Andersson?=

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. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top