How do I replace multiple spaces with a single space in C#? The Next CEO of Stack OverflowHow to trim “ a b c ” into “a b c”check does string contain more than one white spaceReplacing multiple consecutive spaces by a single space in a stringHow to allow user to enter only ONE SPACE after each word?Removing White spaces from string is not working in c#Regex - replace spacesHow to sanitize a string removing specific character?Replace and Split Multiple nRemoving inner duplicate spacesHow to remove all white space from the beginning or end of a string?What is the difference between String and string in C#?Cast int to enum in C#How do I enumerate an enum in C#?Catch multiple exceptions at once?How do I read / convert an InputStream into a String in Java?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I convert a String to an int in Java?

Why didn't Khan get resurrected in the Genesis Explosion?

What can we do to stop prior company from asking us questions?

MessageLevel in QGIS3

How do we know the LHC results are robust?

How to avoid supervisors with prejudiced views?

What does "Its cash flow is deeply negative" mean?

If the heap is initialized for security, then why is the stack uninitialized?

How to make a variable always equal to the result of some calculations?

Can I equip Skullclamp on a creature I am sacrificing?

Why did we only see the N-1 starfighters in one film?

What happened in Rome, when the western empire "fell"?

Why do we use the plural of movies in this phrase "We went to the movies last night."?

Contours of a clandestine nature

Is there a way to save my career from absolute disaster?

Different harmonic changes implied by a simple descending scale

How do scammers retract money, while you can’t?

Unreliable Magic - Is it worth it?

How did the Bene Gesserit know how to make a Kwisatz Haderach?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

How to count occurrences of text in a file?

If Nick Fury and Coulson already knew about aliens (Kree and Skrull) why did they wait until Thor's appearance to start making weapons?

Why do professional authors make "consistency" mistakes? And how to avoid them?

Elegant way to replace substring in a regex with optional groups in Python?

How to transpose the 1st and -1th levels of arbitrarily nested array?



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



The Next CEO of Stack OverflowHow to trim “ a b c ” into “a b c”check does string contain more than one white spaceReplacing multiple consecutive spaces by a single space in a stringHow to allow user to enter only ONE SPACE after each word?Removing White spaces from string is not working in c#Regex - replace spacesHow to sanitize a string removing specific character?Replace and Split Multiple nRemoving inner duplicate spacesHow to remove all white space from the beginning or end of a string?What is the difference between String and string in C#?Cast int to enum in C#How do I enumerate an enum in C#?Catch multiple exceptions at once?How do I read / convert an InputStream into a String in Java?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How do I make the first letter of a string uppercase in JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I convert a String to an int in Java?










392















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









share|improve this question



















  • 1





    a state machine can easily do it, but it's probably overkill if you need it only to remove spaces

    – Adrian
    Jan 6 '12 at 19:20











  • I've added a benchmark on the different ways to do this in a duplicate question stackoverflow.com/a/37592018/582061 . Regex was not the fastest way to do this.

    – Stian Standahl
    Jun 3 '16 at 4:42
















392















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









share|improve this question



















  • 1





    a state machine can easily do it, but it's probably overkill if you need it only to remove spaces

    – Adrian
    Jan 6 '12 at 19:20











  • I've added a benchmark on the different ways to do this in a duplicate question stackoverflow.com/a/37592018/582061 . Regex was not the fastest way to do this.

    – Stian Standahl
    Jun 3 '16 at 4:42














392












392








392


69






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









share|improve this question
















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






c# regex string






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 24 '12 at 3:19









uınbɐɥs

6,30242041




6,30242041










asked Oct 15 '08 at 22:10









PokusPokus

4,090113227




4,090113227







  • 1





    a state machine can easily do it, but it's probably overkill if you need it only to remove spaces

    – Adrian
    Jan 6 '12 at 19:20











  • I've added a benchmark on the different ways to do this in a duplicate question stackoverflow.com/a/37592018/582061 . Regex was not the fastest way to do this.

    – Stian Standahl
    Jun 3 '16 at 4:42













  • 1





    a state machine can easily do it, but it's probably overkill if you need it only to remove spaces

    – Adrian
    Jan 6 '12 at 19:20











  • I've added a benchmark on the different ways to do this in a duplicate question stackoverflow.com/a/37592018/582061 . Regex was not the fastest way to do this.

    – Stian Standahl
    Jun 3 '16 at 4:42








1




1





a state machine can easily do it, but it's probably overkill if you need it only to remove spaces

– Adrian
Jan 6 '12 at 19:20





a state machine can easily do it, but it's probably overkill if you need it only to remove spaces

– Adrian
Jan 6 '12 at 19:20













I've added a benchmark on the different ways to do this in a duplicate question stackoverflow.com/a/37592018/582061 . Regex was not the fastest way to do this.

– Stian Standahl
Jun 3 '16 at 4:42






I've added a benchmark on the different ways to do this in a duplicate question stackoverflow.com/a/37592018/582061 . Regex was not the fastest way to do this.

– Stian Standahl
Jun 3 '16 at 4:42













22 Answers
22






active

oldest

votes


















405














RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]2,", options);
tempo = regex.Replace(tempo, " ");





share|improve this answer




















  • 9





    @Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)

    – paulwhit
    Oct 15 '08 at 23:40






  • 6





    Really, RegEx is overkill for this.

    – Joel Coehoorn
    Oct 28 '08 at 15:01






  • 27





    But now you have 2 problems....

    – seanb
    Nov 20 '08 at 7:24






  • 10





    @Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?

    – Konrad Rudolph
    Nov 23 '08 at 16:27






  • 22





    @Oscar Joel’s code isn’t a simple loop through all characters! It’s a hidden nested loop that has a quadratic worst case. This regular expression, by contrast, is linear, only builds up a single string (= drastically reduced allocation costs compared to Joel’s code) and furthermore the engine can optimize the hell out of it (to be honest, I doubt the .NET regex is smart enough for this but in theory this regular expression can be implemented so cheaply that it’s not even funny any more; it only needs a DFA with three states, one transition each, and no additional information).

    – Konrad Rudolph
    Mar 4 '11 at 10:17



















552














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.






share|improve this answer


















  • 34





    Slight modification: Regex.Replace(source, @"(s)s+", "$1"); This will return the first whitespace type found. So if you have 5 tabs, it will return a tab. Incase someone prefers this.

    – F.B. ten Kate
    May 14 '12 at 12:56











  • @radistao Your link is for Javascript string replace, not for C#.

    – Shiva
    Apr 28 '14 at 17:58






  • 1





    @Shiva, /ss+/ is a standard POSIX regex statement and may be converted/used in any language using own syntax

    – radistao
    Apr 29 '14 at 6:45











  • @F.B.tenKate Good option. A further example is if you have tab-space-space-tab-newline, it will return a tab.

    – goodeye
    Jan 26 '15 at 3:28






  • 2





    In the spirit of @F.B.tenKate's solution: Regex.Replace(source, @"(s)1+", "$1"); will replace multiple identical consecutive characters by a single one.

    – François Beaune
    Jan 11 '16 at 17:06


















38














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





share|improve this answer


















  • 2





    Regex works too.

    – tvanfosson
    Oct 15 '08 at 22:13






  • 3





    This is more readable over regex, i prefer it more because i don't need to learn some other syntax

    – Michael Bahig
    Jul 24 '15 at 11:56






  • 5





    I like it because it doesnt need Regex

    – AleX_
    Dec 22 '15 at 18:08






  • 2





    This would be inefficient for large strings.

    – DarcyThomas
    Sep 28 '16 at 4:05






  • 2





    This also removes leading and trailing spaces.

    – Matzi
    Feb 5 '17 at 21:00


















37














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);





share|improve this answer


















  • 3





    RegexOptions.Multiline changes the meaning of ^ and $ so they match the beginning and end of every line ($ = n), instead of the whole multi-line string. Because s is equivalent to [ fnrtv] the newlines should be replaced even if Multiline option is off.

    – SushiGuy
    Jun 5 '12 at 23:27






  • 1





    Matt's answer has already covered this. I 'believe' 30 persons just blindfold up-voted this answer :)

    – 123iamking
    Sep 8 '17 at 3:50



















23














Another approach which uses LINQ:



 var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
str = string.Join(" ", list);





share|improve this answer






























    21














    It's much simpler than all that:



    while(str.Contains(" ")) str = str.Replace(" ", " ");





    share|improve this answer




















    • 21





      This will be far less efficient than the regex " 2," if the string contains sequences of 3 or more spaces.

      – Jan Goyvaerts
      Nov 20 '08 at 7:22






    • 2





      @JanGoyvaerts: Even with 10 spaces, the regex was slower when I made a quick and dirty test. That being said, it only takes one giant substring full of spaces to completely kill performance of the while loop. For fairness, I used I used RegexOptions.Compiled, rather than the slower Regex.Replace.

      – Brian
      Feb 6 '13 at 15:37







    • 4





      RegexOptions.Compiled adds a lot of overhead compiling the regex into IL. Don't use it unless your application will use the regex often enough or on large enough strings that the increased matching speed offsets the decreased compilation speed.

      – Jan Goyvaerts
      Feb 7 '13 at 4:26


















    19














    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."





    share|improve this answer






























      15














      myString = Regex.Replace(myString, " 2,", " ");





      share|improve this answer






























        9














        For those, who don't like Regex, here is a method that uses the StringBuilder:



         public static string FilterWhiteSpaces(string input)

        if (input == null)
        return string.Empty;

        StringBuilder stringBuilder = new StringBuilder(input.Length);
        for (int i = 0; i < input.Length; i++)

        return stringBuilder.ToString();



        In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.



        Keep in mind, that it does not remove leading or trailing spaces, only multiple occurrences of such.






        share|improve this answer


















        • 1





          This is the best answer for performance

          – The_Black_Smurf
          Feb 27 '18 at 17:35


















        8














        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.






        share|improve this answer




















        • 1





          You have to make sure your string doesn't have "()" or ")(" in it. Or "wel()come to london)(" becomes "wel come to london". You could try using lots of brackets. So use ((((())))) instead of () and )))))((((( instead of )(. It will still work. Still, if the string contains ((((())))) or )))))(((((, this will fail.

          – nmit026
          Jul 26 '17 at 22:18



















        5














        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, " ");





        share|improve this answer
































          5














          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"






          share|improve this answer


















          • 1





            A word of caution : The use of split, while very simple to understand indeed, can have surprisingly negative performance impact. As many strings could be created, you'll have to watch your memory usage in case you handle large strings with this method.

            – Pac0
            Jun 25 '18 at 15:26



















          4














          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 (" ");





          share|improve this answer
































            3














            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 (" ");





            share|improve this answer


















            • 1





              why create an extension method? why not just use string.Join()?

              – Eric Schoonover
              Nov 20 '08 at 3:45


















            2














            I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.



            pattern: (?m:^ +| +$|( )2,)
            replacement: $1


            Its a little difficult to read since we're dealing with empty space, so here it is again with the "spaces" replaced with a "_".



            pattern: (?m:^_+|_+$|(_)2,) <-- don't use this, just for illustration.


            The "(?m:" construct enables the "multi-line" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.






            share|improve this answer






























              1














              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.





              share|improve this answer























              • yes but you would only replace two whitespaces with one. This would not help X number of spaces

                – MGot90
                Jul 26 '16 at 19:59











              • That While loop will take care of all that double spaces to be removed.

                – Learner1947
                Mar 28 '17 at 16:55


















              1














              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)
              i == 0
              return stringBuilder.ToString();








              share|improve this answer






























                1














                try this method



                private string removeNestedWhitespaces(char[] st)

                StringBuilder sb = new StringBuilder();
                int indx = 0, length = st.Length;
                while (indx < length)

                sb.Append(st[indx]);
                indx++;
                while (indx < length && st[indx] == ' ')
                indx++;
                if(sb.Length > 1 && sb[0] != ' ')
                sb.Append(' ');

                return sb.ToString();



                use it like this:



                string test = removeNestedWhitespaces("1 2 3 4 5".toCharArray());





                share|improve this answer

























                • This will remove the trailing spaces

                  – The_Black_Smurf
                  Feb 27 '18 at 19:37











                • sorry for the mistake, i fixed the code, now it's work as expected tested string: " 1 2 3 4 9 " result string: " 1 2 3 4 9 "

                  – Ahmed Aljaff
                  Aug 26 '18 at 22:04


















                0














                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 " ) );





                share|improve this answer


















                • 1





                  Assumes text does not already contain (char)22

                  – onedaywhen
                  Nov 30 '12 at 9:27


















                0














                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.






                share|improve this answer






























                  0














                  Use the regex pattern



                   [ ]+ #only space

                  var text = Regex.Replace(inputString, @"[ ]+", " ");





                  share|improve this answer






























                    0














                    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) =>
                    ).ToString();


                    public static void Main()

                    Console.WriteLine(""" + StringExtension.StripSpaces("1 Hello World 2 ") + """);




                    Input:



                    "1 Hello World 2 "


                    Output:



                    "1 Hello World 2 "





                    share|improve this answer





















                      protected by dippas Sep 10 '16 at 0:18



                      Thank you for your interest in this question.
                      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                      Would you like to answer one of these unanswered questions instead?














                      22 Answers
                      22






                      active

                      oldest

                      votes








                      22 Answers
                      22






                      active

                      oldest

                      votes









                      active

                      oldest

                      votes






                      active

                      oldest

                      votes









                      405














                      RegexOptions options = RegexOptions.None;
                      Regex regex = new Regex("[ ]2,", options);
                      tempo = regex.Replace(tempo, " ");





                      share|improve this answer




















                      • 9





                        @Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)

                        – paulwhit
                        Oct 15 '08 at 23:40






                      • 6





                        Really, RegEx is overkill for this.

                        – Joel Coehoorn
                        Oct 28 '08 at 15:01






                      • 27





                        But now you have 2 problems....

                        – seanb
                        Nov 20 '08 at 7:24






                      • 10





                        @Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?

                        – Konrad Rudolph
                        Nov 23 '08 at 16:27






                      • 22





                        @Oscar Joel’s code isn’t a simple loop through all characters! It’s a hidden nested loop that has a quadratic worst case. This regular expression, by contrast, is linear, only builds up a single string (= drastically reduced allocation costs compared to Joel’s code) and furthermore the engine can optimize the hell out of it (to be honest, I doubt the .NET regex is smart enough for this but in theory this regular expression can be implemented so cheaply that it’s not even funny any more; it only needs a DFA with three states, one transition each, and no additional information).

                        – Konrad Rudolph
                        Mar 4 '11 at 10:17
















                      405














                      RegexOptions options = RegexOptions.None;
                      Regex regex = new Regex("[ ]2,", options);
                      tempo = regex.Replace(tempo, " ");





                      share|improve this answer




















                      • 9





                        @Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)

                        – paulwhit
                        Oct 15 '08 at 23:40






                      • 6





                        Really, RegEx is overkill for this.

                        – Joel Coehoorn
                        Oct 28 '08 at 15:01






                      • 27





                        But now you have 2 problems....

                        – seanb
                        Nov 20 '08 at 7:24






                      • 10





                        @Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?

                        – Konrad Rudolph
                        Nov 23 '08 at 16:27






                      • 22





                        @Oscar Joel’s code isn’t a simple loop through all characters! It’s a hidden nested loop that has a quadratic worst case. This regular expression, by contrast, is linear, only builds up a single string (= drastically reduced allocation costs compared to Joel’s code) and furthermore the engine can optimize the hell out of it (to be honest, I doubt the .NET regex is smart enough for this but in theory this regular expression can be implemented so cheaply that it’s not even funny any more; it only needs a DFA with three states, one transition each, and no additional information).

                        – Konrad Rudolph
                        Mar 4 '11 at 10:17














                      405












                      405








                      405







                      RegexOptions options = RegexOptions.None;
                      Regex regex = new Regex("[ ]2,", options);
                      tempo = regex.Replace(tempo, " ");





                      share|improve this answer















                      RegexOptions options = RegexOptions.None;
                      Regex regex = new Regex("[ ]2,", options);
                      tempo = regex.Replace(tempo, " ");






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Feb 3 '16 at 11:27









                      Sheridan

                      56.1k16113160




                      56.1k16113160










                      answered Oct 15 '08 at 22:11









                      Patrick DesjardinsPatrick Desjardins

                      88.9k77271326




                      88.9k77271326







                      • 9





                        @Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)

                        – paulwhit
                        Oct 15 '08 at 23:40






                      • 6





                        Really, RegEx is overkill for this.

                        – Joel Coehoorn
                        Oct 28 '08 at 15:01






                      • 27





                        But now you have 2 problems....

                        – seanb
                        Nov 20 '08 at 7:24






                      • 10





                        @Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?

                        – Konrad Rudolph
                        Nov 23 '08 at 16:27






                      • 22





                        @Oscar Joel’s code isn’t a simple loop through all characters! It’s a hidden nested loop that has a quadratic worst case. This regular expression, by contrast, is linear, only builds up a single string (= drastically reduced allocation costs compared to Joel’s code) and furthermore the engine can optimize the hell out of it (to be honest, I doubt the .NET regex is smart enough for this but in theory this regular expression can be implemented so cheaply that it’s not even funny any more; it only needs a DFA with three states, one transition each, and no additional information).

                        – Konrad Rudolph
                        Mar 4 '11 at 10:17













                      • 9





                        @Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)

                        – paulwhit
                        Oct 15 '08 at 23:40






                      • 6





                        Really, RegEx is overkill for this.

                        – Joel Coehoorn
                        Oct 28 '08 at 15:01






                      • 27





                        But now you have 2 problems....

                        – seanb
                        Nov 20 '08 at 7:24






                      • 10





                        @Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?

                        – Konrad Rudolph
                        Nov 23 '08 at 16:27






                      • 22





                        @Oscar Joel’s code isn’t a simple loop through all characters! It’s a hidden nested loop that has a quadratic worst case. This regular expression, by contrast, is linear, only builds up a single string (= drastically reduced allocation costs compared to Joel’s code) and furthermore the engine can optimize the hell out of it (to be honest, I doubt the .NET regex is smart enough for this but in theory this regular expression can be implemented so cheaply that it’s not even funny any more; it only needs a DFA with three states, one transition each, and no additional information).

                        – Konrad Rudolph
                        Mar 4 '11 at 10:17








                      9




                      9





                      @Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)

                      – paulwhit
                      Oct 15 '08 at 23:40





                      @Craig a comment would suffice, IMO. // This block replaces multiple spaces with one... :)

                      – paulwhit
                      Oct 15 '08 at 23:40




                      6




                      6





                      Really, RegEx is overkill for this.

                      – Joel Coehoorn
                      Oct 28 '08 at 15:01





                      Really, RegEx is overkill for this.

                      – Joel Coehoorn
                      Oct 28 '08 at 15:01




                      27




                      27





                      But now you have 2 problems....

                      – seanb
                      Nov 20 '08 at 7:24





                      But now you have 2 problems....

                      – seanb
                      Nov 20 '08 at 7:24




                      10




                      10





                      @Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?

                      – Konrad Rudolph
                      Nov 23 '08 at 16:27





                      @Joel: Can't agree. I'm actually sure that this way is more efficient than yours for large enough strings and can be done in one single line. Where's the overkill?

                      – Konrad Rudolph
                      Nov 23 '08 at 16:27




                      22




                      22





                      @Oscar Joel’s code isn’t a simple loop through all characters! It’s a hidden nested loop that has a quadratic worst case. This regular expression, by contrast, is linear, only builds up a single string (= drastically reduced allocation costs compared to Joel’s code) and furthermore the engine can optimize the hell out of it (to be honest, I doubt the .NET regex is smart enough for this but in theory this regular expression can be implemented so cheaply that it’s not even funny any more; it only needs a DFA with three states, one transition each, and no additional information).

                      – Konrad Rudolph
                      Mar 4 '11 at 10:17






                      @Oscar Joel’s code isn’t a simple loop through all characters! It’s a hidden nested loop that has a quadratic worst case. This regular expression, by contrast, is linear, only builds up a single string (= drastically reduced allocation costs compared to Joel’s code) and furthermore the engine can optimize the hell out of it (to be honest, I doubt the .NET regex is smart enough for this but in theory this regular expression can be implemented so cheaply that it’s not even funny any more; it only needs a DFA with three states, one transition each, and no additional information).

                      – Konrad Rudolph
                      Mar 4 '11 at 10:17














                      552














                      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.






                      share|improve this answer


















                      • 34





                        Slight modification: Regex.Replace(source, @"(s)s+", "$1"); This will return the first whitespace type found. So if you have 5 tabs, it will return a tab. Incase someone prefers this.

                        – F.B. ten Kate
                        May 14 '12 at 12:56











                      • @radistao Your link is for Javascript string replace, not for C#.

                        – Shiva
                        Apr 28 '14 at 17:58






                      • 1





                        @Shiva, /ss+/ is a standard POSIX regex statement and may be converted/used in any language using own syntax

                        – radistao
                        Apr 29 '14 at 6:45











                      • @F.B.tenKate Good option. A further example is if you have tab-space-space-tab-newline, it will return a tab.

                        – goodeye
                        Jan 26 '15 at 3:28






                      • 2





                        In the spirit of @F.B.tenKate's solution: Regex.Replace(source, @"(s)1+", "$1"); will replace multiple identical consecutive characters by a single one.

                        – François Beaune
                        Jan 11 '16 at 17:06















                      552














                      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.






                      share|improve this answer


















                      • 34





                        Slight modification: Regex.Replace(source, @"(s)s+", "$1"); This will return the first whitespace type found. So if you have 5 tabs, it will return a tab. Incase someone prefers this.

                        – F.B. ten Kate
                        May 14 '12 at 12:56











                      • @radistao Your link is for Javascript string replace, not for C#.

                        – Shiva
                        Apr 28 '14 at 17:58






                      • 1





                        @Shiva, /ss+/ is a standard POSIX regex statement and may be converted/used in any language using own syntax

                        – radistao
                        Apr 29 '14 at 6:45











                      • @F.B.tenKate Good option. A further example is if you have tab-space-space-tab-newline, it will return a tab.

                        – goodeye
                        Jan 26 '15 at 3:28






                      • 2





                        In the spirit of @F.B.tenKate's solution: Regex.Replace(source, @"(s)1+", "$1"); will replace multiple identical consecutive characters by a single one.

                        – François Beaune
                        Jan 11 '16 at 17:06













                      552












                      552








                      552







                      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.






                      share|improve this answer













                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Oct 15 '08 at 23:58









                      MattMatt

                      24.2k42731




                      24.2k42731







                      • 34





                        Slight modification: Regex.Replace(source, @"(s)s+", "$1"); This will return the first whitespace type found. So if you have 5 tabs, it will return a tab. Incase someone prefers this.

                        – F.B. ten Kate
                        May 14 '12 at 12:56











                      • @radistao Your link is for Javascript string replace, not for C#.

                        – Shiva
                        Apr 28 '14 at 17:58






                      • 1





                        @Shiva, /ss+/ is a standard POSIX regex statement and may be converted/used in any language using own syntax

                        – radistao
                        Apr 29 '14 at 6:45











                      • @F.B.tenKate Good option. A further example is if you have tab-space-space-tab-newline, it will return a tab.

                        – goodeye
                        Jan 26 '15 at 3:28






                      • 2





                        In the spirit of @F.B.tenKate's solution: Regex.Replace(source, @"(s)1+", "$1"); will replace multiple identical consecutive characters by a single one.

                        – François Beaune
                        Jan 11 '16 at 17:06












                      • 34





                        Slight modification: Regex.Replace(source, @"(s)s+", "$1"); This will return the first whitespace type found. So if you have 5 tabs, it will return a tab. Incase someone prefers this.

                        – F.B. ten Kate
                        May 14 '12 at 12:56











                      • @radistao Your link is for Javascript string replace, not for C#.

                        – Shiva
                        Apr 28 '14 at 17:58






                      • 1





                        @Shiva, /ss+/ is a standard POSIX regex statement and may be converted/used in any language using own syntax

                        – radistao
                        Apr 29 '14 at 6:45











                      • @F.B.tenKate Good option. A further example is if you have tab-space-space-tab-newline, it will return a tab.

                        – goodeye
                        Jan 26 '15 at 3:28






                      • 2





                        In the spirit of @F.B.tenKate's solution: Regex.Replace(source, @"(s)1+", "$1"); will replace multiple identical consecutive characters by a single one.

                        – François Beaune
                        Jan 11 '16 at 17:06







                      34




                      34





                      Slight modification: Regex.Replace(source, @"(s)s+", "$1"); This will return the first whitespace type found. So if you have 5 tabs, it will return a tab. Incase someone prefers this.

                      – F.B. ten Kate
                      May 14 '12 at 12:56





                      Slight modification: Regex.Replace(source, @"(s)s+", "$1"); This will return the first whitespace type found. So if you have 5 tabs, it will return a tab. Incase someone prefers this.

                      – F.B. ten Kate
                      May 14 '12 at 12:56













                      @radistao Your link is for Javascript string replace, not for C#.

                      – Shiva
                      Apr 28 '14 at 17:58





                      @radistao Your link is for Javascript string replace, not for C#.

                      – Shiva
                      Apr 28 '14 at 17:58




                      1




                      1





                      @Shiva, /ss+/ is a standard POSIX regex statement and may be converted/used in any language using own syntax

                      – radistao
                      Apr 29 '14 at 6:45





                      @Shiva, /ss+/ is a standard POSIX regex statement and may be converted/used in any language using own syntax

                      – radistao
                      Apr 29 '14 at 6:45













                      @F.B.tenKate Good option. A further example is if you have tab-space-space-tab-newline, it will return a tab.

                      – goodeye
                      Jan 26 '15 at 3:28





                      @F.B.tenKate Good option. A further example is if you have tab-space-space-tab-newline, it will return a tab.

                      – goodeye
                      Jan 26 '15 at 3:28




                      2




                      2





                      In the spirit of @F.B.tenKate's solution: Regex.Replace(source, @"(s)1+", "$1"); will replace multiple identical consecutive characters by a single one.

                      – François Beaune
                      Jan 11 '16 at 17:06





                      In the spirit of @F.B.tenKate's solution: Regex.Replace(source, @"(s)1+", "$1"); will replace multiple identical consecutive characters by a single one.

                      – François Beaune
                      Jan 11 '16 at 17:06











                      38














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





                      share|improve this answer


















                      • 2





                        Regex works too.

                        – tvanfosson
                        Oct 15 '08 at 22:13






                      • 3





                        This is more readable over regex, i prefer it more because i don't need to learn some other syntax

                        – Michael Bahig
                        Jul 24 '15 at 11:56






                      • 5





                        I like it because it doesnt need Regex

                        – AleX_
                        Dec 22 '15 at 18:08






                      • 2





                        This would be inefficient for large strings.

                        – DarcyThomas
                        Sep 28 '16 at 4:05






                      • 2





                        This also removes leading and trailing spaces.

                        – Matzi
                        Feb 5 '17 at 21:00















                      38














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





                      share|improve this answer


















                      • 2





                        Regex works too.

                        – tvanfosson
                        Oct 15 '08 at 22:13






                      • 3





                        This is more readable over regex, i prefer it more because i don't need to learn some other syntax

                        – Michael Bahig
                        Jul 24 '15 at 11:56






                      • 5





                        I like it because it doesnt need Regex

                        – AleX_
                        Dec 22 '15 at 18:08






                      • 2





                        This would be inefficient for large strings.

                        – DarcyThomas
                        Sep 28 '16 at 4:05






                      • 2





                        This also removes leading and trailing spaces.

                        – Matzi
                        Feb 5 '17 at 21:00













                      38












                      38








                      38







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





                      share|improve this answer













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






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Oct 15 '08 at 22:12









                      tvanfossontvanfosson

                      431k82649756




                      431k82649756







                      • 2





                        Regex works too.

                        – tvanfosson
                        Oct 15 '08 at 22:13






                      • 3





                        This is more readable over regex, i prefer it more because i don't need to learn some other syntax

                        – Michael Bahig
                        Jul 24 '15 at 11:56






                      • 5





                        I like it because it doesnt need Regex

                        – AleX_
                        Dec 22 '15 at 18:08






                      • 2





                        This would be inefficient for large strings.

                        – DarcyThomas
                        Sep 28 '16 at 4:05






                      • 2





                        This also removes leading and trailing spaces.

                        – Matzi
                        Feb 5 '17 at 21:00












                      • 2





                        Regex works too.

                        – tvanfosson
                        Oct 15 '08 at 22:13






                      • 3





                        This is more readable over regex, i prefer it more because i don't need to learn some other syntax

                        – Michael Bahig
                        Jul 24 '15 at 11:56






                      • 5





                        I like it because it doesnt need Regex

                        – AleX_
                        Dec 22 '15 at 18:08






                      • 2





                        This would be inefficient for large strings.

                        – DarcyThomas
                        Sep 28 '16 at 4:05






                      • 2





                        This also removes leading and trailing spaces.

                        – Matzi
                        Feb 5 '17 at 21:00







                      2




                      2





                      Regex works too.

                      – tvanfosson
                      Oct 15 '08 at 22:13





                      Regex works too.

                      – tvanfosson
                      Oct 15 '08 at 22:13




                      3




                      3





                      This is more readable over regex, i prefer it more because i don't need to learn some other syntax

                      – Michael Bahig
                      Jul 24 '15 at 11:56





                      This is more readable over regex, i prefer it more because i don't need to learn some other syntax

                      – Michael Bahig
                      Jul 24 '15 at 11:56




                      5




                      5





                      I like it because it doesnt need Regex

                      – AleX_
                      Dec 22 '15 at 18:08





                      I like it because it doesnt need Regex

                      – AleX_
                      Dec 22 '15 at 18:08




                      2




                      2





                      This would be inefficient for large strings.

                      – DarcyThomas
                      Sep 28 '16 at 4:05





                      This would be inefficient for large strings.

                      – DarcyThomas
                      Sep 28 '16 at 4:05




                      2




                      2





                      This also removes leading and trailing spaces.

                      – Matzi
                      Feb 5 '17 at 21:00





                      This also removes leading and trailing spaces.

                      – Matzi
                      Feb 5 '17 at 21:00











                      37














                      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);





                      share|improve this answer


















                      • 3





                        RegexOptions.Multiline changes the meaning of ^ and $ so they match the beginning and end of every line ($ = n), instead of the whole multi-line string. Because s is equivalent to [ fnrtv] the newlines should be replaced even if Multiline option is off.

                        – SushiGuy
                        Jun 5 '12 at 23:27






                      • 1





                        Matt's answer has already covered this. I 'believe' 30 persons just blindfold up-voted this answer :)

                        – 123iamking
                        Sep 8 '17 at 3:50
















                      37














                      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);





                      share|improve this answer


















                      • 3





                        RegexOptions.Multiline changes the meaning of ^ and $ so they match the beginning and end of every line ($ = n), instead of the whole multi-line string. Because s is equivalent to [ fnrtv] the newlines should be replaced even if Multiline option is off.

                        – SushiGuy
                        Jun 5 '12 at 23:27






                      • 1





                        Matt's answer has already covered this. I 'believe' 30 persons just blindfold up-voted this answer :)

                        – 123iamking
                        Sep 8 '17 at 3:50














                      37












                      37








                      37







                      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);





                      share|improve this answer













                      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);






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 20 '10 at 22:07









                      Brenda BellBrenda Bell

                      37132




                      37132







                      • 3





                        RegexOptions.Multiline changes the meaning of ^ and $ so they match the beginning and end of every line ($ = n), instead of the whole multi-line string. Because s is equivalent to [ fnrtv] the newlines should be replaced even if Multiline option is off.

                        – SushiGuy
                        Jun 5 '12 at 23:27






                      • 1





                        Matt's answer has already covered this. I 'believe' 30 persons just blindfold up-voted this answer :)

                        – 123iamking
                        Sep 8 '17 at 3:50













                      • 3





                        RegexOptions.Multiline changes the meaning of ^ and $ so they match the beginning and end of every line ($ = n), instead of the whole multi-line string. Because s is equivalent to [ fnrtv] the newlines should be replaced even if Multiline option is off.

                        – SushiGuy
                        Jun 5 '12 at 23:27






                      • 1





                        Matt's answer has already covered this. I 'believe' 30 persons just blindfold up-voted this answer :)

                        – 123iamking
                        Sep 8 '17 at 3:50








                      3




                      3





                      RegexOptions.Multiline changes the meaning of ^ and $ so they match the beginning and end of every line ($ = n), instead of the whole multi-line string. Because s is equivalent to [ fnrtv] the newlines should be replaced even if Multiline option is off.

                      – SushiGuy
                      Jun 5 '12 at 23:27





                      RegexOptions.Multiline changes the meaning of ^ and $ so they match the beginning and end of every line ($ = n), instead of the whole multi-line string. Because s is equivalent to [ fnrtv] the newlines should be replaced even if Multiline option is off.

                      – SushiGuy
                      Jun 5 '12 at 23:27




                      1




                      1





                      Matt's answer has already covered this. I 'believe' 30 persons just blindfold up-voted this answer :)

                      – 123iamking
                      Sep 8 '17 at 3:50






                      Matt's answer has already covered this. I 'believe' 30 persons just blindfold up-voted this answer :)

                      – 123iamking
                      Sep 8 '17 at 3:50












                      23














                      Another approach which uses LINQ:



                       var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
                      str = string.Join(" ", list);





                      share|improve this answer



























                        23














                        Another approach which uses LINQ:



                         var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
                        str = string.Join(" ", list);





                        share|improve this answer

























                          23












                          23








                          23







                          Another approach which uses LINQ:



                           var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
                          str = string.Join(" ", list);





                          share|improve this answer













                          Another approach which uses LINQ:



                           var list = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
                          str = string.Join(" ", list);






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Aug 14 '12 at 7:23









                          cuonglecuongle

                          56.4k25116173




                          56.4k25116173





















                              21














                              It's much simpler than all that:



                              while(str.Contains(" ")) str = str.Replace(" ", " ");





                              share|improve this answer




















                              • 21





                                This will be far less efficient than the regex " 2," if the string contains sequences of 3 or more spaces.

                                – Jan Goyvaerts
                                Nov 20 '08 at 7:22






                              • 2





                                @JanGoyvaerts: Even with 10 spaces, the regex was slower when I made a quick and dirty test. That being said, it only takes one giant substring full of spaces to completely kill performance of the while loop. For fairness, I used I used RegexOptions.Compiled, rather than the slower Regex.Replace.

                                – Brian
                                Feb 6 '13 at 15:37







                              • 4





                                RegexOptions.Compiled adds a lot of overhead compiling the regex into IL. Don't use it unless your application will use the regex often enough or on large enough strings that the increased matching speed offsets the decreased compilation speed.

                                – Jan Goyvaerts
                                Feb 7 '13 at 4:26















                              21














                              It's much simpler than all that:



                              while(str.Contains(" ")) str = str.Replace(" ", " ");





                              share|improve this answer




















                              • 21





                                This will be far less efficient than the regex " 2," if the string contains sequences of 3 or more spaces.

                                – Jan Goyvaerts
                                Nov 20 '08 at 7:22






                              • 2





                                @JanGoyvaerts: Even with 10 spaces, the regex was slower when I made a quick and dirty test. That being said, it only takes one giant substring full of spaces to completely kill performance of the while loop. For fairness, I used I used RegexOptions.Compiled, rather than the slower Regex.Replace.

                                – Brian
                                Feb 6 '13 at 15:37







                              • 4





                                RegexOptions.Compiled adds a lot of overhead compiling the regex into IL. Don't use it unless your application will use the regex often enough or on large enough strings that the increased matching speed offsets the decreased compilation speed.

                                – Jan Goyvaerts
                                Feb 7 '13 at 4:26













                              21












                              21








                              21







                              It's much simpler than all that:



                              while(str.Contains(" ")) str = str.Replace(" ", " ");





                              share|improve this answer















                              It's much simpler than all that:



                              while(str.Contains(" ")) str = str.Replace(" ", " ");






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 8 '12 at 7:09









                              Fahim Parkar

                              20.7k34133241




                              20.7k34133241










                              answered Oct 15 '08 at 23:36









                              Joel CoehoornJoel Coehoorn

                              312k96497735




                              312k96497735







                              • 21





                                This will be far less efficient than the regex " 2," if the string contains sequences of 3 or more spaces.

                                – Jan Goyvaerts
                                Nov 20 '08 at 7:22






                              • 2





                                @JanGoyvaerts: Even with 10 spaces, the regex was slower when I made a quick and dirty test. That being said, it only takes one giant substring full of spaces to completely kill performance of the while loop. For fairness, I used I used RegexOptions.Compiled, rather than the slower Regex.Replace.

                                – Brian
                                Feb 6 '13 at 15:37







                              • 4





                                RegexOptions.Compiled adds a lot of overhead compiling the regex into IL. Don't use it unless your application will use the regex often enough or on large enough strings that the increased matching speed offsets the decreased compilation speed.

                                – Jan Goyvaerts
                                Feb 7 '13 at 4:26












                              • 21





                                This will be far less efficient than the regex " 2," if the string contains sequences of 3 or more spaces.

                                – Jan Goyvaerts
                                Nov 20 '08 at 7:22






                              • 2





                                @JanGoyvaerts: Even with 10 spaces, the regex was slower when I made a quick and dirty test. That being said, it only takes one giant substring full of spaces to completely kill performance of the while loop. For fairness, I used I used RegexOptions.Compiled, rather than the slower Regex.Replace.

                                – Brian
                                Feb 6 '13 at 15:37







                              • 4





                                RegexOptions.Compiled adds a lot of overhead compiling the regex into IL. Don't use it unless your application will use the regex often enough or on large enough strings that the increased matching speed offsets the decreased compilation speed.

                                – Jan Goyvaerts
                                Feb 7 '13 at 4:26







                              21




                              21





                              This will be far less efficient than the regex " 2," if the string contains sequences of 3 or more spaces.

                              – Jan Goyvaerts
                              Nov 20 '08 at 7:22





                              This will be far less efficient than the regex " 2," if the string contains sequences of 3 or more spaces.

                              – Jan Goyvaerts
                              Nov 20 '08 at 7:22




                              2




                              2





                              @JanGoyvaerts: Even with 10 spaces, the regex was slower when I made a quick and dirty test. That being said, it only takes one giant substring full of spaces to completely kill performance of the while loop. For fairness, I used I used RegexOptions.Compiled, rather than the slower Regex.Replace.

                              – Brian
                              Feb 6 '13 at 15:37






                              @JanGoyvaerts: Even with 10 spaces, the regex was slower when I made a quick and dirty test. That being said, it only takes one giant substring full of spaces to completely kill performance of the while loop. For fairness, I used I used RegexOptions.Compiled, rather than the slower Regex.Replace.

                              – Brian
                              Feb 6 '13 at 15:37





                              4




                              4





                              RegexOptions.Compiled adds a lot of overhead compiling the regex into IL. Don't use it unless your application will use the regex often enough or on large enough strings that the increased matching speed offsets the decreased compilation speed.

                              – Jan Goyvaerts
                              Feb 7 '13 at 4:26





                              RegexOptions.Compiled adds a lot of overhead compiling the regex into IL. Don't use it unless your application will use the regex often enough or on large enough strings that the increased matching speed offsets the decreased compilation speed.

                              – Jan Goyvaerts
                              Feb 7 '13 at 4:26











                              19














                              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."





                              share|improve this answer



























                                19














                                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."





                                share|improve this answer

























                                  19












                                  19








                                  19







                                  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."





                                  share|improve this answer













                                  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."






                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Nov 20 '15 at 2:00









                                  ScubaSteveScubaSteve

                                  3,94443647




                                  3,94443647





















                                      15














                                      myString = Regex.Replace(myString, " 2,", " ");





                                      share|improve this answer



























                                        15














                                        myString = Regex.Replace(myString, " 2,", " ");





                                        share|improve this answer

























                                          15












                                          15








                                          15







                                          myString = Regex.Replace(myString, " 2,", " ");





                                          share|improve this answer













                                          myString = Regex.Replace(myString, " 2,", " ");






                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Nov 20 '08 at 7:20









                                          Jan GoyvaertsJan Goyvaerts

                                          17k64763




                                          17k64763





















                                              9














                                              For those, who don't like Regex, here is a method that uses the StringBuilder:



                                               public static string FilterWhiteSpaces(string input)

                                              if (input == null)
                                              return string.Empty;

                                              StringBuilder stringBuilder = new StringBuilder(input.Length);
                                              for (int i = 0; i < input.Length; i++)

                                              return stringBuilder.ToString();



                                              In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.



                                              Keep in mind, that it does not remove leading or trailing spaces, only multiple occurrences of such.






                                              share|improve this answer


















                                              • 1





                                                This is the best answer for performance

                                                – The_Black_Smurf
                                                Feb 27 '18 at 17:35















                                              9














                                              For those, who don't like Regex, here is a method that uses the StringBuilder:



                                               public static string FilterWhiteSpaces(string input)

                                              if (input == null)
                                              return string.Empty;

                                              StringBuilder stringBuilder = new StringBuilder(input.Length);
                                              for (int i = 0; i < input.Length; i++)

                                              return stringBuilder.ToString();



                                              In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.



                                              Keep in mind, that it does not remove leading or trailing spaces, only multiple occurrences of such.






                                              share|improve this answer


















                                              • 1





                                                This is the best answer for performance

                                                – The_Black_Smurf
                                                Feb 27 '18 at 17:35













                                              9












                                              9








                                              9







                                              For those, who don't like Regex, here is a method that uses the StringBuilder:



                                               public static string FilterWhiteSpaces(string input)

                                              if (input == null)
                                              return string.Empty;

                                              StringBuilder stringBuilder = new StringBuilder(input.Length);
                                              for (int i = 0; i < input.Length; i++)

                                              return stringBuilder.ToString();



                                              In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.



                                              Keep in mind, that it does not remove leading or trailing spaces, only multiple occurrences of such.






                                              share|improve this answer













                                              For those, who don't like Regex, here is a method that uses the StringBuilder:



                                               public static string FilterWhiteSpaces(string input)

                                              if (input == null)
                                              return string.Empty;

                                              StringBuilder stringBuilder = new StringBuilder(input.Length);
                                              for (int i = 0; i < input.Length; i++)

                                              return stringBuilder.ToString();



                                              In my tests, this method was 16 times faster on average with a very large set of small-to-medium sized strings, compared to a static compiled Regex. Compared to a non-compiled or non-static Regex, this should be even faster.



                                              Keep in mind, that it does not remove leading or trailing spaces, only multiple occurrences of such.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered May 27 '13 at 15:16









                                              NolonarNolonar

                                              4,36422749




                                              4,36422749







                                              • 1





                                                This is the best answer for performance

                                                – The_Black_Smurf
                                                Feb 27 '18 at 17:35












                                              • 1





                                                This is the best answer for performance

                                                – The_Black_Smurf
                                                Feb 27 '18 at 17:35







                                              1




                                              1





                                              This is the best answer for performance

                                              – The_Black_Smurf
                                              Feb 27 '18 at 17:35





                                              This is the best answer for performance

                                              – The_Black_Smurf
                                              Feb 27 '18 at 17:35











                                              8














                                              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.






                                              share|improve this answer




















                                              • 1





                                                You have to make sure your string doesn't have "()" or ")(" in it. Or "wel()come to london)(" becomes "wel come to london". You could try using lots of brackets. So use ((((())))) instead of () and )))))((((( instead of )(. It will still work. Still, if the string contains ((((())))) or )))))(((((, this will fail.

                                                – nmit026
                                                Jul 26 '17 at 22:18
















                                              8














                                              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.






                                              share|improve this answer




















                                              • 1





                                                You have to make sure your string doesn't have "()" or ")(" in it. Or "wel()come to london)(" becomes "wel come to london". You could try using lots of brackets. So use ((((())))) instead of () and )))))((((( instead of )(. It will still work. Still, if the string contains ((((())))) or )))))(((((, this will fail.

                                                – nmit026
                                                Jul 26 '17 at 22:18














                                              8












                                              8








                                              8







                                              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.






                                              share|improve this answer















                                              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.







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jun 24 '15 at 16:51

























                                              answered Mar 6 '15 at 10:37









                                              ravish.hackerravish.hacker

                                              628918




                                              628918







                                              • 1





                                                You have to make sure your string doesn't have "()" or ")(" in it. Or "wel()come to london)(" becomes "wel come to london". You could try using lots of brackets. So use ((((())))) instead of () and )))))((((( instead of )(. It will still work. Still, if the string contains ((((())))) or )))))(((((, this will fail.

                                                – nmit026
                                                Jul 26 '17 at 22:18













                                              • 1





                                                You have to make sure your string doesn't have "()" or ")(" in it. Or "wel()come to london)(" becomes "wel come to london". You could try using lots of brackets. So use ((((())))) instead of () and )))))((((( instead of )(. It will still work. Still, if the string contains ((((())))) or )))))(((((, this will fail.

                                                – nmit026
                                                Jul 26 '17 at 22:18








                                              1




                                              1





                                              You have to make sure your string doesn't have "()" or ")(" in it. Or "wel()come to london)(" becomes "wel come to london". You could try using lots of brackets. So use ((((())))) instead of () and )))))((((( instead of )(. It will still work. Still, if the string contains ((((())))) or )))))(((((, this will fail.

                                              – nmit026
                                              Jul 26 '17 at 22:18






                                              You have to make sure your string doesn't have "()" or ")(" in it. Or "wel()come to london)(" becomes "wel come to london". You could try using lots of brackets. So use ((((())))) instead of () and )))))((((( instead of )(. It will still work. Still, if the string contains ((((())))) or )))))(((((, this will fail.

                                              – nmit026
                                              Jul 26 '17 at 22:18












                                              5














                                              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, " ");





                                              share|improve this answer





























                                                5














                                                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, " ");





                                                share|improve this answer



























                                                  5












                                                  5








                                                  5







                                                  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, " ");





                                                  share|improve this answer















                                                  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, " ");






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Oct 16 '17 at 18:14









                                                  Aleks Andreev

                                                  5,01272334




                                                  5,01272334










                                                  answered May 14 '15 at 6:44









                                                  somebodysomebody

                                                  411916




                                                  411916





















                                                      5














                                                      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"






                                                      share|improve this answer


















                                                      • 1





                                                        A word of caution : The use of split, while very simple to understand indeed, can have surprisingly negative performance impact. As many strings could be created, you'll have to watch your memory usage in case you handle large strings with this method.

                                                        – Pac0
                                                        Jun 25 '18 at 15:26
















                                                      5














                                                      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"






                                                      share|improve this answer


















                                                      • 1





                                                        A word of caution : The use of split, while very simple to understand indeed, can have surprisingly negative performance impact. As many strings could be created, you'll have to watch your memory usage in case you handle large strings with this method.

                                                        – Pac0
                                                        Jun 25 '18 at 15:26














                                                      5












                                                      5








                                                      5







                                                      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"






                                                      share|improve this answer













                                                      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"







                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Jan 18 '18 at 16:39









                                                      Stephen du BuisStephen du Buis

                                                      7316




                                                      7316







                                                      • 1





                                                        A word of caution : The use of split, while very simple to understand indeed, can have surprisingly negative performance impact. As many strings could be created, you'll have to watch your memory usage in case you handle large strings with this method.

                                                        – Pac0
                                                        Jun 25 '18 at 15:26













                                                      • 1





                                                        A word of caution : The use of split, while very simple to understand indeed, can have surprisingly negative performance impact. As many strings could be created, you'll have to watch your memory usage in case you handle large strings with this method.

                                                        – Pac0
                                                        Jun 25 '18 at 15:26








                                                      1




                                                      1





                                                      A word of caution : The use of split, while very simple to understand indeed, can have surprisingly negative performance impact. As many strings could be created, you'll have to watch your memory usage in case you handle large strings with this method.

                                                      – Pac0
                                                      Jun 25 '18 at 15:26






                                                      A word of caution : The use of split, while very simple to understand indeed, can have surprisingly negative performance impact. As many strings could be created, you'll have to watch your memory usage in case you handle large strings with this method.

                                                      – Pac0
                                                      Jun 25 '18 at 15:26












                                                      4














                                                      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 (" ");





                                                      share|improve this answer





























                                                        4














                                                        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 (" ");





                                                        share|improve this answer



























                                                          4












                                                          4








                                                          4







                                                          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 (" ");





                                                          share|improve this answer















                                                          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 (" ");






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Oct 15 '08 at 22:55

























                                                          answered Oct 15 '08 at 22:39









                                                          Jay BazuziJay Bazuzi

                                                          31.6k1094157




                                                          31.6k1094157





















                                                              3














                                                              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 (" ");





                                                              share|improve this answer


















                                                              • 1





                                                                why create an extension method? why not just use string.Join()?

                                                                – Eric Schoonover
                                                                Nov 20 '08 at 3:45















                                                              3














                                                              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 (" ");





                                                              share|improve this answer


















                                                              • 1





                                                                why create an extension method? why not just use string.Join()?

                                                                – Eric Schoonover
                                                                Nov 20 '08 at 3:45













                                                              3












                                                              3








                                                              3







                                                              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 (" ");





                                                              share|improve this answer













                                                              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 (" ");






                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Oct 20 '08 at 17:40









                                                              Jay BazuziJay Bazuzi

                                                              31.6k1094157




                                                              31.6k1094157







                                                              • 1





                                                                why create an extension method? why not just use string.Join()?

                                                                – Eric Schoonover
                                                                Nov 20 '08 at 3:45












                                                              • 1





                                                                why create an extension method? why not just use string.Join()?

                                                                – Eric Schoonover
                                                                Nov 20 '08 at 3:45







                                                              1




                                                              1





                                                              why create an extension method? why not just use string.Join()?

                                                              – Eric Schoonover
                                                              Nov 20 '08 at 3:45





                                                              why create an extension method? why not just use string.Join()?

                                                              – Eric Schoonover
                                                              Nov 20 '08 at 3:45











                                                              2














                                                              I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.



                                                              pattern: (?m:^ +| +$|( )2,)
                                                              replacement: $1


                                                              Its a little difficult to read since we're dealing with empty space, so here it is again with the "spaces" replaced with a "_".



                                                              pattern: (?m:^_+|_+$|(_)2,) <-- don't use this, just for illustration.


                                                              The "(?m:" construct enables the "multi-line" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.






                                                              share|improve this answer



























                                                                2














                                                                I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.



                                                                pattern: (?m:^ +| +$|( )2,)
                                                                replacement: $1


                                                                Its a little difficult to read since we're dealing with empty space, so here it is again with the "spaces" replaced with a "_".



                                                                pattern: (?m:^_+|_+$|(_)2,) <-- don't use this, just for illustration.


                                                                The "(?m:" construct enables the "multi-line" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.






                                                                share|improve this answer

























                                                                  2












                                                                  2








                                                                  2







                                                                  I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.



                                                                  pattern: (?m:^ +| +$|( )2,)
                                                                  replacement: $1


                                                                  Its a little difficult to read since we're dealing with empty space, so here it is again with the "spaces" replaced with a "_".



                                                                  pattern: (?m:^_+|_+$|(_)2,) <-- don't use this, just for illustration.


                                                                  The "(?m:" construct enables the "multi-line" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.






                                                                  share|improve this answer













                                                                  I know this is pretty old, but ran across this while trying to accomplish almost the same thing. Found this solution in RegEx Buddy. This pattern will replace all double spaces with single spaces and also trim leading and trailing spaces.



                                                                  pattern: (?m:^ +| +$|( )2,)
                                                                  replacement: $1


                                                                  Its a little difficult to read since we're dealing with empty space, so here it is again with the "spaces" replaced with a "_".



                                                                  pattern: (?m:^_+|_+$|(_)2,) <-- don't use this, just for illustration.


                                                                  The "(?m:" construct enables the "multi-line" option. I generally like to include whatever options I can within the pattern itself so it is more self contained.







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Jul 20 '14 at 5:07









                                                                  Paul EasterPaul Easter

                                                                  48955




                                                                  48955





















                                                                      1














                                                                      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.





                                                                      share|improve this answer























                                                                      • yes but you would only replace two whitespaces with one. This would not help X number of spaces

                                                                        – MGot90
                                                                        Jul 26 '16 at 19:59











                                                                      • That While loop will take care of all that double spaces to be removed.

                                                                        – Learner1947
                                                                        Mar 28 '17 at 16:55















                                                                      1














                                                                      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.





                                                                      share|improve this answer























                                                                      • yes but you would only replace two whitespaces with one. This would not help X number of spaces

                                                                        – MGot90
                                                                        Jul 26 '16 at 19:59











                                                                      • That While loop will take care of all that double spaces to be removed.

                                                                        – Learner1947
                                                                        Mar 28 '17 at 16:55













                                                                      1












                                                                      1








                                                                      1







                                                                      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.





                                                                      share|improve this answer













                                                                      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.






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Feb 11 '16 at 10:24









                                                                      Learner1947Learner1947

                                                                      276




                                                                      276












                                                                      • yes but you would only replace two whitespaces with one. This would not help X number of spaces

                                                                        – MGot90
                                                                        Jul 26 '16 at 19:59











                                                                      • That While loop will take care of all that double spaces to be removed.

                                                                        – Learner1947
                                                                        Mar 28 '17 at 16:55

















                                                                      • yes but you would only replace two whitespaces with one. This would not help X number of spaces

                                                                        – MGot90
                                                                        Jul 26 '16 at 19:59











                                                                      • That While loop will take care of all that double spaces to be removed.

                                                                        – Learner1947
                                                                        Mar 28 '17 at 16:55
















                                                                      yes but you would only replace two whitespaces with one. This would not help X number of spaces

                                                                      – MGot90
                                                                      Jul 26 '16 at 19:59





                                                                      yes but you would only replace two whitespaces with one. This would not help X number of spaces

                                                                      – MGot90
                                                                      Jul 26 '16 at 19:59













                                                                      That While loop will take care of all that double spaces to be removed.

                                                                      – Learner1947
                                                                      Mar 28 '17 at 16:55





                                                                      That While loop will take care of all that double spaces to be removed.

                                                                      – Learner1947
                                                                      Mar 28 '17 at 16:55











                                                                      1














                                                                      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)
                                                                      i == 0
                                                                      return stringBuilder.ToString();








                                                                      share|improve this answer



























                                                                        1














                                                                        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)
                                                                        i == 0
                                                                        return stringBuilder.ToString();








                                                                        share|improve this answer

























                                                                          1












                                                                          1








                                                                          1







                                                                          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)
                                                                          i == 0
                                                                          return stringBuilder.ToString();








                                                                          share|improve this answer













                                                                          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)
                                                                          i == 0
                                                                          return stringBuilder.ToString();









                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Feb 27 '18 at 20:04









                                                                          The_Black_SmurfThe_Black_Smurf

                                                                          3,955123959




                                                                          3,955123959





















                                                                              1














                                                                              try this method



                                                                              private string removeNestedWhitespaces(char[] st)

                                                                              StringBuilder sb = new StringBuilder();
                                                                              int indx = 0, length = st.Length;
                                                                              while (indx < length)

                                                                              sb.Append(st[indx]);
                                                                              indx++;
                                                                              while (indx < length && st[indx] == ' ')
                                                                              indx++;
                                                                              if(sb.Length > 1 && sb[0] != ' ')
                                                                              sb.Append(' ');

                                                                              return sb.ToString();



                                                                              use it like this:



                                                                              string test = removeNestedWhitespaces("1 2 3 4 5".toCharArray());





                                                                              share|improve this answer

























                                                                              • This will remove the trailing spaces

                                                                                – The_Black_Smurf
                                                                                Feb 27 '18 at 19:37











                                                                              • sorry for the mistake, i fixed the code, now it's work as expected tested string: " 1 2 3 4 9 " result string: " 1 2 3 4 9 "

                                                                                – Ahmed Aljaff
                                                                                Aug 26 '18 at 22:04















                                                                              1














                                                                              try this method



                                                                              private string removeNestedWhitespaces(char[] st)

                                                                              StringBuilder sb = new StringBuilder();
                                                                              int indx = 0, length = st.Length;
                                                                              while (indx < length)

                                                                              sb.Append(st[indx]);
                                                                              indx++;
                                                                              while (indx < length && st[indx] == ' ')
                                                                              indx++;
                                                                              if(sb.Length > 1 && sb[0] != ' ')
                                                                              sb.Append(' ');

                                                                              return sb.ToString();



                                                                              use it like this:



                                                                              string test = removeNestedWhitespaces("1 2 3 4 5".toCharArray());





                                                                              share|improve this answer

























                                                                              • This will remove the trailing spaces

                                                                                – The_Black_Smurf
                                                                                Feb 27 '18 at 19:37











                                                                              • sorry for the mistake, i fixed the code, now it's work as expected tested string: " 1 2 3 4 9 " result string: " 1 2 3 4 9 "

                                                                                – Ahmed Aljaff
                                                                                Aug 26 '18 at 22:04













                                                                              1












                                                                              1








                                                                              1







                                                                              try this method



                                                                              private string removeNestedWhitespaces(char[] st)

                                                                              StringBuilder sb = new StringBuilder();
                                                                              int indx = 0, length = st.Length;
                                                                              while (indx < length)

                                                                              sb.Append(st[indx]);
                                                                              indx++;
                                                                              while (indx < length && st[indx] == ' ')
                                                                              indx++;
                                                                              if(sb.Length > 1 && sb[0] != ' ')
                                                                              sb.Append(' ');

                                                                              return sb.ToString();



                                                                              use it like this:



                                                                              string test = removeNestedWhitespaces("1 2 3 4 5".toCharArray());





                                                                              share|improve this answer















                                                                              try this method



                                                                              private string removeNestedWhitespaces(char[] st)

                                                                              StringBuilder sb = new StringBuilder();
                                                                              int indx = 0, length = st.Length;
                                                                              while (indx < length)

                                                                              sb.Append(st[indx]);
                                                                              indx++;
                                                                              while (indx < length && st[indx] == ' ')
                                                                              indx++;
                                                                              if(sb.Length > 1 && sb[0] != ' ')
                                                                              sb.Append(' ');

                                                                              return sb.ToString();



                                                                              use it like this:



                                                                              string test = removeNestedWhitespaces("1 2 3 4 5".toCharArray());






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Aug 26 '18 at 22:02

























                                                                              answered Jan 22 '16 at 18:26









                                                                              Ahmed AljaffAhmed Aljaff

                                                                              369




                                                                              369












                                                                              • This will remove the trailing spaces

                                                                                – The_Black_Smurf
                                                                                Feb 27 '18 at 19:37











                                                                              • sorry for the mistake, i fixed the code, now it's work as expected tested string: " 1 2 3 4 9 " result string: " 1 2 3 4 9 "

                                                                                – Ahmed Aljaff
                                                                                Aug 26 '18 at 22:04

















                                                                              • This will remove the trailing spaces

                                                                                – The_Black_Smurf
                                                                                Feb 27 '18 at 19:37











                                                                              • sorry for the mistake, i fixed the code, now it's work as expected tested string: " 1 2 3 4 9 " result string: " 1 2 3 4 9 "

                                                                                – Ahmed Aljaff
                                                                                Aug 26 '18 at 22:04
















                                                                              This will remove the trailing spaces

                                                                              – The_Black_Smurf
                                                                              Feb 27 '18 at 19:37





                                                                              This will remove the trailing spaces

                                                                              – The_Black_Smurf
                                                                              Feb 27 '18 at 19:37













                                                                              sorry for the mistake, i fixed the code, now it's work as expected tested string: " 1 2 3 4 9 " result string: " 1 2 3 4 9 "

                                                                              – Ahmed Aljaff
                                                                              Aug 26 '18 at 22:04





                                                                              sorry for the mistake, i fixed the code, now it's work as expected tested string: " 1 2 3 4 9 " result string: " 1 2 3 4 9 "

                                                                              – Ahmed Aljaff
                                                                              Aug 26 '18 at 22:04











                                                                              0














                                                                              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 " ) );





                                                                              share|improve this answer


















                                                                              • 1





                                                                                Assumes text does not already contain (char)22

                                                                                – onedaywhen
                                                                                Nov 30 '12 at 9:27















                                                                              0














                                                                              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 " ) );





                                                                              share|improve this answer


















                                                                              • 1





                                                                                Assumes text does not already contain (char)22

                                                                                – onedaywhen
                                                                                Nov 30 '12 at 9:27













                                                                              0












                                                                              0








                                                                              0







                                                                              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 " ) );





                                                                              share|improve this answer













                                                                              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 " ) );






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Nov 30 '12 at 9:26









                                                                              onedaywhenonedaywhen

                                                                              44k1079122




                                                                              44k1079122







                                                                              • 1





                                                                                Assumes text does not already contain (char)22

                                                                                – onedaywhen
                                                                                Nov 30 '12 at 9:27












                                                                              • 1





                                                                                Assumes text does not already contain (char)22

                                                                                – onedaywhen
                                                                                Nov 30 '12 at 9:27







                                                                              1




                                                                              1





                                                                              Assumes text does not already contain (char)22

                                                                              – onedaywhen
                                                                              Nov 30 '12 at 9:27





                                                                              Assumes text does not already contain (char)22

                                                                              – onedaywhen
                                                                              Nov 30 '12 at 9:27











                                                                              0














                                                                              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.






                                                                              share|improve this answer



























                                                                                0














                                                                                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.






                                                                                share|improve this answer

























                                                                                  0












                                                                                  0








                                                                                  0







                                                                                  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.






                                                                                  share|improve this answer













                                                                                  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.







                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Feb 16 '16 at 18:38









                                                                                  Tom GullenTom Gullen

                                                                                  34k70242407




                                                                                  34k70242407





















                                                                                      0














                                                                                      Use the regex pattern



                                                                                       [ ]+ #only space

                                                                                      var text = Regex.Replace(inputString, @"[ ]+", " ");





                                                                                      share|improve this answer



























                                                                                        0














                                                                                        Use the regex pattern



                                                                                         [ ]+ #only space

                                                                                        var text = Regex.Replace(inputString, @"[ ]+", " ");





                                                                                        share|improve this answer

























                                                                                          0












                                                                                          0








                                                                                          0







                                                                                          Use the regex pattern



                                                                                           [ ]+ #only space

                                                                                          var text = Regex.Replace(inputString, @"[ ]+", " ");





                                                                                          share|improve this answer













                                                                                          Use the regex pattern



                                                                                           [ ]+ #only space

                                                                                          var text = Regex.Replace(inputString, @"[ ]+", " ");






                                                                                          share|improve this answer












                                                                                          share|improve this answer



                                                                                          share|improve this answer










                                                                                          answered Aug 23 '18 at 14:50









                                                                                          M.HassanM.Hassan

                                                                                          4,31722539




                                                                                          4,31722539





















                                                                                              0














                                                                                              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) =>
                                                                                              ).ToString();


                                                                                              public static void Main()

                                                                                              Console.WriteLine(""" + StringExtension.StripSpaces("1 Hello World 2 ") + """);




                                                                                              Input:



                                                                                              "1 Hello World 2 "


                                                                                              Output:



                                                                                              "1 Hello World 2 "





                                                                                              share|improve this answer



























                                                                                                0














                                                                                                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) =>
                                                                                                ).ToString();


                                                                                                public static void Main()

                                                                                                Console.WriteLine(""" + StringExtension.StripSpaces("1 Hello World 2 ") + """);




                                                                                                Input:



                                                                                                "1 Hello World 2 "


                                                                                                Output:



                                                                                                "1 Hello World 2 "





                                                                                                share|improve this answer

























                                                                                                  0












                                                                                                  0








                                                                                                  0







                                                                                                  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) =>
                                                                                                  ).ToString();


                                                                                                  public static void Main()

                                                                                                  Console.WriteLine(""" + StringExtension.StripSpaces("1 Hello World 2 ") + """);




                                                                                                  Input:



                                                                                                  "1 Hello World 2 "


                                                                                                  Output:



                                                                                                  "1 Hello World 2 "





                                                                                                  share|improve this answer













                                                                                                  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) =>
                                                                                                  ).ToString();


                                                                                                  public static void Main()

                                                                                                  Console.WriteLine(""" + StringExtension.StripSpaces("1 Hello World 2 ") + """);




                                                                                                  Input:



                                                                                                  "1 Hello World 2 "


                                                                                                  Output:



                                                                                                  "1 Hello World 2 "






                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Nov 28 '18 at 13:11









                                                                                                  Patrick ArtnerPatrick Artner

                                                                                                  25.9k62544




                                                                                                  25.9k62544















                                                                                                      protected by dippas Sep 10 '16 at 0:18



                                                                                                      Thank you for your interest in this question.
                                                                                                      Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                      Would you like to answer one of these unanswered questions instead?