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

前端 未结 24 1412
面向向阳花
面向向阳花 2020-11-22 06:37

How can I replace multiple spaces in a string with only one space in C#?

Example:

1 2 3  4    5

would be:

1 2 3 4 5         


        
24条回答
  •  无人及你
    2020-11-22 07:22

    This is a shorter version, which should only be used if you are only doing this once, as it creates a new instance of the Regex class every time it is called.

    temp = new Regex(" {2,}").Replace(temp, " "); 
    

    If you are not too acquainted with regular expressions, here's a short explanation:

    The {2,} makes the regex search for the character preceding it, and finds substrings between 2 and unlimited times.
    The .Replace(temp, " ") replaces all matches in the string temp with a space.

    If you want to use this multiple times, here is a better option, as it creates the regex IL at compile time:

    Regex singleSpacify = new Regex(" {2,}", RegexOptions.Compiled);
    temp = singleSpacify.Replace(temp, " ");
    

提交回复
热议问题