Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use LINQ to strip repeating spaces from a string?

A quick brain teaser: given a string

This  is a string with  repeating   spaces

What would be the LINQ expressing to end up with

This is a string with repeating spaces

Thanks!

For reference, here's one non-LINQ way:

private static IEnumerable<char> RemoveRepeatingSpaces(IEnumerable<char> text)
{
  bool isSpace = false;
  foreach (var c in text)
  {
    if (isSpace && char.IsWhiteSpace(c)) continue;

    isSpace = char.IsWhiteSpace(c);
    yield return c;
  }
}
like image 496
Michael Teper Avatar asked Nov 27 '22 18:11

Michael Teper


1 Answers

This is not a linq type task, use regex

string output = Regex.Replace(input," +"," ");

Of course you could use linq to apply this to a collection of strings.

like image 72
Paul Creasey Avatar answered Jan 23 '23 15:01

Paul Creasey