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

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

    Many answers are providing the right output but for those looking for the best performances, I did improve Nolanar's answer (which was the best answer for performance) by about 10%.

    public static string MergeSpaces(this string str)
    {
    
        if (str == null)
        {
            return null;
        }
        else
        {
            StringBuilder stringBuilder = new StringBuilder(str.Length);
    
            int i = 0;
            foreach (char c in str)
            {
                if (c != ' ' || i == 0 || str[i - 1] != ' ')
                    stringBuilder.Append(c);
                i++;
            }
            return stringBuilder.ToString();
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 07:06

    Regex can be rather slow even with simple tasks. This creates an extension method that can be used off of any string.

        public static class StringExtension
        {
            public static String ReduceWhitespace(this String value)
            {
                var newString = new StringBuilder();
                bool previousIsWhitespace = false;
                for (int i = 0; i < value.Length; i++)
                {
                    if (Char.IsWhiteSpace(value[i]))
                    {
                        if (previousIsWhitespace)
                        {
                            continue;
                        }
    
                        previousIsWhitespace = true;
                    }
                    else
                    {
                        previousIsWhitespace = false;
                    }
    
                    newString.Append(value[i]);
                }
    
                return newString.ToString();
            }
        }
    

    It would be used as such:

    string testValue = "This contains     too          much  whitespace."
    testValue = testValue.ReduceWhitespace();
    // testValue = "This contains too much whitespace."
    
    0 讨论(0)
  • 2020-11-22 07:07

    no Regex, no Linq... removes leading and trailing spaces as well as reducing any embedded multiple space segments to one space

    string myString = "   0 1 2  3   4               5  ";
    myString = string.Join(" ", myString.Split(new char[] { ' ' }, 
    StringSplitOptions.RemoveEmptyEntries));
    

    result:"0 1 2 3 4 5"

    0 讨论(0)
  • 2020-11-22 07:08

    Mix of StringBuilder and Enumerable.Aggregate() as extension method for strings:

    using System;
    using System.Linq;
    using System.Text;
    
    public static class StringExtension
    {
        public static string StripSpaces(this string s)
        {
            return s.Aggregate(new StringBuilder(), (acc, c) =>
            {
                if (c != ' ' || acc.Length > 0 && acc[acc.Length-1] != ' ')
                    acc.Append(c);
    
                return acc;
            }).ToString();
        }
    
        public static void Main()
        {
            Console.WriteLine("\"" + StringExtension.StripSpaces("1   Hello       World  2   ") + "\"");
        }
    }
    

    Input:

    "1   Hello       World  2   "
    

    Output:

    "1 Hello World 2 "
    
    0 讨论(0)
  • 2020-11-22 07:11

    I just wrote a new Join that I like, so I thought I'd re-answer, with it:

    public static string Join<T>(this IEnumerable<T> source, string separator)
    {
        return string.Join(separator, source.Select(e => e.ToString()).ToArray());
    }
    

    One of the cool things about this is that it work with collections that aren't strings, by calling ToString() on the elements. Usage is still the same:

    //...
    
    string s = "     1  2    4 5".Split (
        " ".ToCharArray(), 
        StringSplitOptions.RemoveEmptyEntries
        ).Join (" ");
    
    0 讨论(0)
  • 2020-11-22 07:13

    Another approach which uses LINQ:

     var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
     str = string.Join(" ", list);
    
    0 讨论(0)
提交回复
热议问题