locked
Replace multiple spaces in a string in multiple places to just one space? RRS feed

  • Question

  • User1820622718 posted

    I have a multiline text box that I allow my users to enter or paste information that I upload to my database.

    I want to replace an carriage returns to a single space and I'm doing that with this code

    string sList = txtBulk.Text.Replace("\n", " ").Replace("\r\n", " ") ;

    I need to also replace multiple spaces with a single space.  How can I do this?

    If a user enters:

    "THIS          IS          A TEST"  I need it to transform to "THIS IS A TEST".

    Thank you

    Friday, June 13, 2014 9:34 AM

Answers

  • User-492460945 posted

    This worked for me..

    string test = "THIS          IS          A TEST";
    Response.Write(test.Replace("  ", " "));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 13, 2014 9:42 AM

All replies

  • User-492460945 posted

    This worked for me..

    string test = "THIS          IS          A TEST";
    Response.Write(test.Replace("  ", " "));

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, June 13, 2014 9:42 AM
  • User2103319870 posted

    You can also try with the LINQ approach to remove mutliple spaces and add only a single space.

    Sample Code:

                    //Your sample string
    		string strvalue ="THIS          IS          A TEST";
    //Split the words based on white sapce var list = strvalue.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s));
    //Join the values back and add a single space in between strvalue = string.Join(" ", list);
    Friday, June 13, 2014 1:46 PM
  • User1820622718 posted

    Thank you

    Friday, June 13, 2014 3:09 PM