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

前端 未结 24 1407
面向向阳花
面向向阳花 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:17

    Old skool:

    string oldText = "   1 2  3   4    5     ";
    string newText = oldText
                        .Replace("  ", " " + (char)22 )
                        .Replace( (char)22 + " ", "" )
                        .Replace( (char)22 + "", "" );
    
    Assert.That( newText, Is.EqualTo( " 1 2 3 4 5 " ) );
    
    0 讨论(0)
  • 2020-11-22 07:18

    Without using regular expressions:

    while (myString.IndexOf("  ", StringComparison.CurrentCulture) != -1)
    {
        myString = myString.Replace("  ", " ");
    }
    

    OK to use on short strings, but will perform badly on long strings with lots of spaces.

    0 讨论(0)
  • 2020-11-22 07:21
    string sentence = "This is a sentence with multiple    spaces";
    RegexOptions options = RegexOptions.None;
    Regex regex = new Regex("[ ]{2,}", options);     
    sentence = regex.Replace(sentence, " ");
    
    0 讨论(0)
  • 2020-11-22 07:22

    I like to use:

    myString = Regex.Replace(myString, @"\s+", " ");
    

    Since it will catch runs of any kind of whitespace (e.g. tabs, newlines, etc.) and replace them with a single space.

    0 讨论(0)
  • 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, " ");
    
    0 讨论(0)
  • 2020-11-22 07:23
    string xyz = "1   2   3   4   5";
    xyz = string.Join( " ", xyz.Split( new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries ));
    
    0 讨论(0)
提交回复
热议问题