Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. var pattern = @" +"; // match two or more spaces
  2. var groups = Regex.Split(input, pattern);
  3.  
  4. var tokens = groups.Select(group => group.Replace(" ", String.Empty));
  5.  
  6. var result = String.Join(' ', tokens.ToArray());
  7.  
  8. // Replace all single whitespaces
  9. for (int i = 0; i < sourceString.Length; i++)
  10. {
  11. if (sourceString[i] = ' ')
  12. {
  13. if (i < sourceString.Length - 1 && sourceString[i+1] != ' ')
  14. sourceString = sourceString.Delete(i);
  15. }
  16. }
  17.  
  18. // Replace multiple whitespaces
  19. while (sourceString.Contains(" ")) // Two spaces here!
  20. sourceString = sourceString.Replace(" ", " ");
  21.  
  22. string str = "abc def ghi xyz";
  23. var result = str.Split(); //This will remove single spaces from the result
  24. StringBuilder sb = new StringBuilder();
  25. bool ifMultipleSpacesFound = false;
  26. for (int i = 0; i < result.Length;i++)
  27. {
  28. if (!String.IsNullOrWhiteSpace(result[i]))
  29. {
  30. sb.Append(result[i]);
  31. ifMultipleSpacesFound = false;
  32. }
  33. else
  34. {
  35. if (!ifMultipleSpacesFound)
  36. {
  37. ifMultipleSpacesFound = true;
  38. sb.Append(" ");
  39. }
  40. }
  41. }
  42.  
  43. string output = sb.ToString();
  44.  
  45. output = "abcdefghi xyz"
  46.  
  47. public static string RemoveUnwantedSpaces(string text)
  48. {
  49. var sb = new StringBuilder();
  50. char lhs = '';
  51. char mid = '';
  52.  
  53. foreach (char rhs in text)
  54. {
  55. if (rhs != ' ' || (mid == ' ' && lhs != ' '))
  56. sb.Append(rhs);
  57.  
  58. lhs = mid;
  59. mid = rhs;
  60. }
  61.  
  62. return sb.ToString().Trim();
  63. }
  64.  
  65. Regex.Replace("abc def ghi xyz", "( )( )*([^ ])", "$2$3")
  66.  
  67. var tmp = Regex.Replace("abc def ghi xyz", "( )([^ ])", "$2")
  68.  
  69. var result = Regex.Replace(tmp, "( )+", " ");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement