0

Refactoring existing code.

They are trying to collapse any series of spaces in string passed in to a single space.

Surely there is a better way.

        for (int i = 0; i < 25; i++)
        {
            str = str.Replace("  ", " ");
        }
BWhite
  • 713
  • 1
  • 7
  • 24

2 Answers2

2
System.Text.RegularExpressions.Regex.Replace(str,@"\s+"," ");
haldo
  • 14,512
  • 5
  • 46
  • 52
Mikael
  • 1,002
  • 1
  • 11
  • 22
0

Split the string using

List<string> spiltList = yourStr.Split(' ').ToList();

Remove empty string from collection.

spiltList.RemoveAll(e => string.IsNullOrWhiteSpace(e));

Join the list of strings to a single string

string result = string.Join(" ", spiltList);
Sushant Yelpale
  • 860
  • 6
  • 19
  • None of this code will compile. First off there is no static `Split` method on `String`. I assume you meant something like `yourString.Split(" ");`. Second there is no overload of `string.Split` that takes a single string. You can pass a single `char` or an array of strings and a `StringSplitOptions`. Speaking of which you can use `StringSplitOptions.RemoveEmptyEntries` to remove the empties. Second array does not have a `remove` method and if it did you'd want to remove empty strings not a one space string. Finally it's `string.Join`. – juharr Nov 16 '19 at 04:38
  • 1
    So I believe the answer you were going for is `str = string.Join(" ", str.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries));` – juharr Nov 16 '19 at 04:43