C# .NET - space removing in csharp.. - Asked By shah zeb on 10-Oct-11 09:57 AM

How can i easily remove white spaces from a string.
I tried the below method but it does not works for me.
What are my different options?

if any body can specify me a regular expression for this sort of task i will be thank ful


string abc = "The Quick brown           fox   jumps over     the lazy   dog";

string[] array = abc.Split();

// string abc2 = string.Join(" ",array);

string abc2 = string.Empty;

for (int i = 0; i < array.Length ; i++)


abc2 += array[i].Trim() + " ";




Jitendra Faye replied to shah zeb on 10-Oct-11 10:02 AM
To replace space in string use this code-

string abc = "The Quick brown       fox   jumps over   the lazy   dog";

string removed= abc.replace(" ","");

Try this code and let me know.
shah zeb replied to Jitendra Faye on 10-Oct-11 10:10 AM
thanks vickey for a quick reply.
What is need is
The Quick brown     fox   jumps over   the lazy   dog.
i want to bring the above written line in some regular format like.
The Quick brown fox jumps over the lazy dog.

I hope you got my point

Thank U
dipa ahuja replied to shah zeb on 10-Oct-11 02:11 PM
Simplest way is to use the Trim function

string abc = "The Quick brown       fox   jumps over   the lazy   dog";

The Quick brown fox jumps over the lazy dog
Devil Scorpio replied to shah zeb on 10-Oct-11 02:32 PM
Hi Shah,

Program that removes whitespace [C#]

using System;
using System.Text.RegularExpressions;

class Program
    static void Main()
    // A.
    // Example strings with multiple whitespaces.
    string s1 = "He saw   a cute\tdog.";
    string s2 = "There\n\twas another sentence.";

    // B.
    // Create the Regex.
    Regex r = new Regex(@"\s+");

    // C.
    // Strip multiple spaces.
    string s3 = r.Replace(s1, @" ");

    // D.
    // Strip multiple spaces.
    string s4 = r.Replace(s2, @" ");


He saw a cute dog.
There was another sentence.
He saw a cute dog.
Reena Jain replied to shah zeb on 10-Oct-11 03:52 PM

simply use trim to remove the unwanted space from the string

here is the example for you

string abc = "The Quick brown       fox   jumps over   the lazy   dog";

this will remain  only single  space in place of multiple space
try this and let me know
shah zeb replied to Devil Scorpio on 11-Oct-11 03:19 AM
Thanks alot.

I need this sort of thing.