Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying replace multiple space into single space but new line text not to replace.
The new line text as it is on that line...?

e.g
hi How r u?
Fine..!!

I want the output as follows:-

hi How r u?
Fine..!!

When I use this code

TextBox2.Text = Regex.Replace(str, " {2,}", " ");
the output come as follows:

hi How r u?Fine..!!
Posted

C#
string input = "your   input   string";
StringBuilder sb = new StringBuilder(input.Length);
bool spaceAdded = false;
for (int i=0; i<input.Length; i++)
{
    char c = input[i];
    if (c == ' ')
    {
        if (!spaceAdded)
        {
            sb.Append(' ');
            spaceAdded = true;
        }
    }
    else
    {
        sb.Append(c);
        spaceAdded = false;
    }
}
string output = sb.ToString();
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900