Let's say I have a string such as:
"Hello how are you doing?"
I would like a function that turns multiple spaces into one space.
So I would get:
"Hello how are you doing?"
I know I could use regex or call
string s = "Hello how are you doing?".replace(" "," ");
But I would have to call it multiple times to make sure all sequential whitespaces are replaced with only one.
Is there already a built in method for this?
string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");
While the existing answers are fine, I'd like to point out one approach which doesn't work:
public static string DontUseThisToCollapseSpaces(string text)
{
while (text.IndexOf(" ") != -1)
{
text = text.Replace(" ", " ");
}
return text;
}
This can loop forever. Anyone care to guess why? (I only came across this when it was asked as a newsgroup question a few years ago... someone actually ran into it as a problem.)
A regular expressoin would be the easiest way. If you write the regex the correct way, you wont need multiple calls.
Change it to this:
string s = System.Text.RegularExpressions.Regex.Replace(s, @"\s{2,}", " ");
Here is the Solution i work with. Without RegEx and String.Split.
public static string TrimWhiteSpace(this string Value)
{
StringBuilder sbOut = new StringBuilder();
if (!string.IsNullOrEmpty(Value))
{
bool IsWhiteSpace = false;
for (int i = 0; i < Value.Length; i++)
{
if (char.IsWhiteSpace(Value[i])) //Comparion with WhiteSpace
{
if (!IsWhiteSpace) //Comparison with previous Char
{
sbOut.Append(Value[i]);
IsWhiteSpace = true;
}
}
else
{
IsWhiteSpace = false;
sbOut.Append(Value[i]);
}
}
}
return sbOut.ToString();
}
so you can:
string cleanedString = dirtyString.TrimWhiteSpace();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With