31

How to remove whitespaces between characters in c#?

Trim() can be used to remove the empty spaces at the beginning of the string as well as at the end. For example " C Sharp ".Trim() results "C Sharp".

But how to make the string into CSharp? We can remove the space using a for or a for each loop along with a temporary variable. But is there any built in method in C#(.Net framework 3.5) to do this like Trim()?

Richard
  • 106,783
  • 21
  • 203
  • 265
Thorin Oakenshield
  • 14,232
  • 33
  • 106
  • 146

10 Answers10

63

You could use String.Replace method

string str = "C Sharp";
str = str.Replace(" ", "");

or if you want to remove all whitespace characters (space, tabs, line breaks...)

string str = "C Sharp";
str = Regex.Replace(str, @"\s", "");
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
Julien Hoarau
  • 48,964
  • 20
  • 128
  • 117
12

If you want to keep one space between every word. You can do it this way as well:

string.Join(" ", inputText.Split(new char[0], StringSplitOptions.RemoveEmptyEntries).ToList().Select(x => x.Trim()));
Reyan Chougle
  • 4,917
  • 2
  • 30
  • 57
4

Use String.Replace to replace all white space with nothing.

eg

string newString = myString.Replace(" ", "");
Iain Ward
  • 9,850
  • 5
  • 34
  • 41
  • 2
    That just replaces (ascii) space, not all whitespace? See discussion here http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx – The Archetypal Paul Oct 11 '10 at 10:07
  • @Paul Discussion where? That link is about String.Trim – Iain Ward Oct 11 '10 at 10:10
  • @Richard Whoops forgot, have fixed this – Iain Ward Oct 11 '10 at 10:10
  • @Pual I take your point, but his example suggests he simply means spaces, not whitespace in general – Iain Ward Oct 11 '10 at 10:11
  • @w69rdy: ok, down vote removed... except SO is not seeing your edit (within 5min) but blocking my un-down vote :-( Now with your edit I can remove it. – Richard Oct 11 '10 at 10:12
  • @w69rdy - read further down about the characters Trim removes. The OP seemed to me to want the equivalent of Trim for all whitespace. – The Archetypal Paul Oct 11 '10 at 10:19
  • @Paul I disagree, he only compares it to Trim in terms of functionality, not specifics. His example suggests he's only interested in spaces and he never mentions anything about other forms of whitespace. If he was I would have thought he would of made that a lot clearer – Iain Ward Oct 11 '10 at 10:30
4

if you want to remove all spaces in one word:

input.Trim().Replace(" ","")

And If you want to remove extra spaces in the sentence, you should use below:

input.Trim().Replace(" +","")

the regex " +", would check if there is one ore more following space characters in the text and replace them with one space.

Jaimil Patel
  • 1,301
  • 6
  • 13
Neda Rezaei
  • 81
  • 1
  • 5
3

If you want to keep one space between every word. this should do it..

 public static string TrimSpacesBetweenString(string s)
    {
        var mystring  =s.RemoveTandNs().Split(new string[] {" "}, StringSplitOptions.None);
        string result = string.Empty;
        foreach (var mstr in mystring)
        {
            var ss = mstr.Trim();
            if (!string.IsNullOrEmpty(ss))
            {
                result = result + ss+" ";
            }
        }
        return result.Trim();

    }

it will remove the string in between the string so if the input is

var s ="c           sharp";
result will be "c sharp";
Parminder
  • 3,088
  • 6
  • 37
  • 61
2
var str="  c sharp  "; str = str.Trim();
        str = Regex.Replace(str, @"\s+", " ");  ///"c sharp"
Mekala V
  • 31
  • 5
1

I found this method great for doing things like building a class that utilizes a calculated property to take lets say a "productName" and stripping the whitespace out to create a URL that will equal an image that uses the productname with no spaces. For instance:

    namespace XXX.Models
    {
        public class Product
        {
            public int ProductID { get; set; }
            public string ProductName { get; set; }
            public string ProductDescription { get; set; }

            public string ProductImage
            {
                get { return ProductName.Replace(" ", string.Empty) + ".jpg"; }
            }
        }
    }

So in this answer I have used a very similar method as w69rdy, but used it in an example, plus I used string.Empty instead of "". And although after .Net 2.0 there is no difference, I find it much easier to read and understand for others who might need to read my code. I also prefer this because I sometimes get lost in all the quotes I might have in a code block.

Eric Bishard
  • 5,201
  • 7
  • 51
  • 75
1
//Remove spaces from a string just using substring method and a for loop 
static void Main(string[] args)
{
    string businessName;
    string newBusinessName = "";
    int i;

    Write("Enter a business name >>> ");
    businessName = ReadLine();

    for(i = 0; i < businessName.Length; i++)
    {
        if (businessName.Substring(i, 1) != " ")
        {
            newBusinessName += businessName.Substring(i, 1);
        }
    } 

    WriteLine("A cool web site name could be www.{0}.com", newBusinessName);
}
yanckst
  • 438
  • 4
  • 17
Dave
  • 11
  • 1
  • For longer strings, it's preferable to use `StringBuilder` rather than `+=`, as it doesn't recreate the String object with each concatenation. – Thane Plummer Sep 07 '16 at 19:43
1

Aditional Answer:

To remove two or more consecutive spaces from a string, you can use regular expressions

string originalString = "This   is    a   string  with  multiple  spaces.";
string modifiedString = Regex.Replace(originalString, @"\s{2,}", " ");

and Output:

This is a string with multiple spaces.
AliT
  • 31
  • 7
0
string myString = "C Sharp".Replace(" ", "");
Andy Rose
  • 16,770
  • 7
  • 43
  • 49