Written code does not work.

I try to solve in LINQPad:

void Main() { Debug.Assert(Foo("Is this a problem?") == "Is this a problem?", "Test # 1"); Debug.Assert(Foo(" Is this a problem?") == "Is this a problem?", "Test # 2"); Debug.Assert(Foo(" Is this a problem? ") == "Is this a problem?", "Test # 4"); Debug.Assert(Foo(" Is this a problem? ") == "Is this a problem?", "Test # 5"); Debug.Assert(Foo(" Is this a problem? ") == "Is this a problem?", "Test # 6"); } string Foo(string s) { s = s.Replace(" ",""); return s; } 
  • What is the question? - Vlad from Moscow
  • My method does not work - stasynyo
  • Your method actually removes all spaces. - Vlad from Moscow

2 answers 2

Two possible options with regular expressions (I suspect that the first option will be faster, but not sure), the first with .Trim() :

 s = Regex.Replace(s, @"\s{2,}", " ").Trim(); 

The second without:

 s = Regex.Replace(s, @"^\s+|\s+$|\s+(?=\s)", ""); 

If you need speed, the expression, of course, is better to compile in advance:

 Regex regex = new Regex(@"^\s+|\s+$|\s+(?=\s)", RegexOptions.Compiled); s = regex.Replace(s, ""); 
  • I do not even understand what is happening there Oo - stasynyo
  • @stasynyo, obviously replacing spaces in a row - Grundy
  • expressions work differently with spaces at the beginning and end of a line - Grundy
  • @stasynyo, \s - any space (normal, tab, all that); {2,} - repeat the previous character / group two times or more. In general, I strongly recommend that you familiarize yourself with regular expressions more closely, very conveniently. - Surfin Bird
  • @SurfinBird thank you very much, just for the first time I see similar constructions @"^\s+|\s+$|\s+(?=\s - stasynyo

The same can be done using this method:

 public static string Foo(string s) { return String.Join(" ", s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)); } 

If you need the Foo method only for comparing strings, and it doesn’t matter to you to use the == operator, you can do it with this method:

 public static bool AreEqual(string s1, string s2) { char[] space = { ' ' }; return s1.Split(space, StringSplitOptions.RemoveEmptyEntries) .SequenceEqual(s2.Split(space, StringSplitOptions.RemoveEmptyEntries)); } 

Using:

 Debug.Assert(AreEqual(" Is this a problem? ", "Is this a problem?"), "Test # 1"); 
  • one
    and it was possible to make the first line Join through a space to return from the function and compare it by == - Grundy
  • @Grundy Right! Thanks, I'll add it now. - Dmitry D.