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

前端 未结 24 1405
面向向阳花
面向向阳花 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 06:59

    It's much simpler than all that:

    while(str.Contains("  ")) str = str.Replace("  ", " ");
    
    0 讨论(0)
  • 2020-11-22 06:59

    Consolodating other answers, per Joel, and hopefully improving slightly as I go:

    You can do this with Regex.Replace():

    string s = Regex.Replace (
        "   1  2    4 5", 
        @"[ ]{2,}", 
        " "
        );
    

    Or with String.Split():

    static class StringExtensions
    {
        public static string Join(this IList<string> value, string separator)
        {
            return string.Join(separator, value.ToArray());
        }
    }
    
    //...
    
    string s = "     1  2    4 5".Split (
        " ".ToCharArray(), 
        StringSplitOptions.RemoveEmptyEntries
        ).Join (" ");
    
    0 讨论(0)
  • 2020-11-22 06:59

    I can remove whitespaces with this

    while word.contains("  ")  //double space
       word = word.Replace("  "," "); //replace double space by single space.
    word = word.trim(); //to remove single whitespces from start & end.
    
    0 讨论(0)
  • 2020-11-22 07:00

    I think Matt's answer is the best, but I don't believe it's quite right. If you want to replace newlines, you must use:

    myString = Regex.Replace(myString, @"\s+", " ", RegexOptions.Multiline);
    
    0 讨论(0)
  • 2020-11-22 07:01
    // Mysample string
    string str ="hi you           are          a demo";
    
    //Split the words based on white sapce
    var demo= str .Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
            
    //Join the values back and add a single space in between
    str = string.Join(" ", demo);
    // output: string str ="hi you are a demo";
    
    0 讨论(0)
  • 2020-11-22 07:04

    You can simply do this in one line solution!

    string s = "welcome to  london";
    s.Replace(" ", "()").Replace(")(", "").Replace("()", " ");
    

    You can choose other brackets (or even other characters) if you like.

    0 讨论(0)
提交回复
热议问题