Stripping spaces and newline characters

  • Thread starter Thread starter Thor W Hammer
  • Start date Start date
T

Thor W Hammer

Smart algorithm for normalizing strings anyone?

Example:
If the original string looks like this:
"the brown
fox "

I want it end up like this:
"the brown fox"


Thanx in advance
 
Thor,

I think the smartest (and perhaps the most efficient) would be to use a
regular expression and then perform a replace operation. However, I don't
know the regular expression you would use. So, in lieu of that, I would use
the Split method on the string class and then insert the spaces myself in
between the individual elements.

Hope this helps.
 
Hi Thor,

str.Trim().Replace("\n", " " );

will do the trick


Cheers,
 
I don't think it will change multiple white-spaces between words to single
white-spaces.
 
However since my string was a well-formed xml document I did it like this
instead:

public string Normalize(string s)
{
XmlDocument d=new XmlDocument();
d.LoadXml(s);
return d.OuterXml;
}
 
Hi Thor,

Yes, you are right about that :)

Sorry, I did not saw it on your example, but if you get really complex then
you will have to take into account things like a tab ( \b ) so the
"normalization" can become quite complex ;)

Cheers,
 
Back
Top