How to remove spaces inside a string in C#.net?

Hello All,

We are supposed to create a Word doc file for our client that is to be used for printing a large list of names and addresses. I am facing the below problem in my C#.net Application.

Eg.

I am reading the values from the Access Database and showing it in the MS Word Document using C#.net windows Application.

The original name looks like: "Michelle Accuso-Stevens"

From DataBase side the name looks like this.

Mich el le Acc uso-Ste ve ns [some spaces inside the string]

foreach (DataRow myRow in dsContacts.Tables[0].Rows)

{

if ("" != myRow["FirstName"].ToString() || "" != myRow["LastName"].ToString().Trim())

{

if ("" != myRow["Title"].ToString())

{

sw.Write(myRow["Title"].ToString() + " ");

}

if ("" != myRow["FirstName"].ToString().Trim())

{

sw.Write(myRow["FirstName"].ToString().Trim() + " ");

}

if ("" != myRow["LastName"].ToString())

{

sw.Write(myRow["LastName"].ToString());

}

sw.WriteLine();

}

How Can I replace the spaces inside the string

Could you please share your ideas on my query as soon as possible

Thanks and Regards

Madhu.P



Answer this question

How to remove spaces inside a string in C#.net?

  • pavel989

    Have a look at the Replace function on the String class...


  • bishoycom

    Hi Sriram,

    Thanks for your suggestion.

    xyz.Replace(" ", string.empty); This line solved my problem.

    Thanks and Regards

    Madhu


  • David Rudolph

    Hi

    Looking at your string it seems 2 spaces got added inbetween your string, so ill suggest replace 2 spaces with a empty string.

    xyz.Replace(" ", string.empty);

    Hope this helps



  • How to remove spaces inside a string in C#.net?