This is a discussion on Removing multiple spaces from string within the C# Programming forums, part of the Software Development category; Hi, Could anyone tell me how to remove the multiple spaces in a string...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Hi bluesky, Use the regular expression to remove multiple spaces in a string // i have a variable amount of spaces between each word in this string string test = "Womens and mens in a palace"; // replaces runs of multiple spaces with a single space test = Regex.Replace(test, @"\s{2,}", " "); // displays new string MessageBox.Show(test); I hope this would help for u |
| |||
| removing double-spaces from strings // input string string s = "blah blah"; // temporary for holding the string prior to replacing string olds; // repeatedly replace strings of 2 spaces with a single space // until the result after replacement is the same as before, // which implies that all spaces must be single spaces do { olds = s; s = s.Replace(" ", " "); } while (olds != s); // now, s == "blah blah" What bothers me about this solution is that it would be rather inefficient, particular for long strings, due to the way the .Net runtime deals with strings (given my current understanding anyway.) Some sort of StringBuilder or char array solution would probably be better I think. |
| |||
| public static string RemoveWhiteSpace(string line) { return Regex.Replace(line, "\\s+", " "); } private void button5_Click(object sender, EventArgs e) { string line = "This is ksdfj an example."; Content.Text = Form1.RemoveWhiteSpace(line); } |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| XML and white spaces | Sathish Kumar | XML and SOAP | 2 | 03-14-2008 03:33 AM |
| Removing duplicate rows in a DataSet | shaalini | ASP and ASP.NET Programming | 2 | 02-13-2008 09:33 PM |
| What is diffrenece between string.compare and string.compareordinal | shaalini | ASP and ASP.NET Programming | 3 | 12-28-2007 10:46 PM |
| Trim Trailing and Leading Spaces using different databases | srikumar_l | Database Support | 0 | 12-05-2007 03:17 AM |
| Info on removing pages history | Jeyaseelansarc | PHP Programming | 2 | 09-25-2007 09:04 AM |