code_junkie

How do I replace multiple spaces with a single space in C#?

Nov 11th, 2011
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. Example "1 2 3 4 5" would be : "1 2 3 4 5"?
  2.  
  3. RegexOptions options = RegexOptions.None;
  4. Regex regex = new Regex(@"[ ]{2,}", options);
  5. tempo = regex.Replace(tempo, @" ");
  6.  
  7. myString = Regex.Replace(myString, @"s+", " ");
  8.  
  9. string xyz = "1 2 3 4 5";
  10. xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
  11.  
  12. while(str.Contains(" ")) str = str.Replace(" ", " ");
  13.  
  14. myString = Regex.Replace(myString, " {2,}", " ");
  15.  
  16. myString = Regex.Replace(myString, @"s+", " ", RegexOptions.Multiline);
  17.  
  18. string s = Regex.Replace (
  19. " 1 2 4 5",
  20. @"[ ]{2,}",
  21. " "
  22. );
  23.  
  24. static class StringExtensions
  25. {
  26. public static string Join(this IList<string> value, string separator)
  27. {
  28. return string.Join(separator, value.ToArray());
  29. }
  30. }
  31.  
  32. //...
  33.  
  34. string s = " 1 2 4 5".Split (
  35. " ".ToCharArray(),
  36. StringSplitOptions.RemoveEmptyEntries
  37. ).Join (" ");
  38.  
  39. public static string Join<T>(this IEnumerable<T> source, string separator)
  40. {
  41. return string.Join(separator, source.Select(e => e.ToString()).ToArray());
  42. }
  43.  
  44. //...
  45.  
  46. string s = " 1 2 4 5".Split (
  47. " ".ToCharArray(),
  48. StringSplitOptions.RemoveEmptyEntries
  49. ).Join (" ");
  50.  
  51. while (str.IndexOf(" ") != -1)
  52. str = str.Replace(" ", " ");
Add Comment
Please, Sign In to add comment