0

How can i make sure the spaces between words in a sentence are identical, using C#?

Example

What are     you looking for 

should be

what are you looking for

Kind regards

Arianule
  • 8,811
  • 45
  • 116
  • 174
  • 1
    `string result = Regex.Replace(source, @"\s{2,}", " ");` to replace each *two or more whitespaces* match into a *single space* – Dmitry Bychenko Oct 13 '17 at 07:35
  • 1
    Please update your spec. It is not clear if you still need to take care about words in the sentence, the capitals and so on. – Yaugen Vlasau Oct 13 '17 at 07:37
  • `string str = string.Join(" ", "What are you looking for ".ToLower().Split(' ').Where(s => s != ""));` – SᴇM Oct 13 '17 at 07:51
  • @SeM-ՍեՄ - see also [StringSplitOptions](https://msdn.microsoft.com/library/system.stringsplitoptions.aspx) - `string str = string.Join(" ", "What are you looking for ".Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries));` – Corak Oct 13 '17 at 08:01
  • @SeM-ՍեՄ - but it seems your way is a few ns faster than using `StringSplitOptions`. On the other hand, from the ways discussed in https://stackoverflow.com/questions/6442421/c-sharp-fastest-way-to-remove-extra-white-spaces I don't know if I implemented the `StringBuilder` way correctly, but using a compiled(!) Regex was about twice as fast as your way. (My `StringBuilder` implementation took about 1.3 times the time of the compiled Regex; which would be vastly different from the observations in that question; but they probably didn't use a *compiled* Regex). Tested with BenchmarkDotNet – Corak Oct 13 '17 at 08:50
  • @Corak yeap, as said [this comment](https://stackoverflow.com/questions/6442421/c-sharp-fastest-way-to-remove-extra-white-spaces#comment7563505_6442477) from _duplicate answer_ . – SᴇM Oct 13 '17 at 08:53

0 Answers0