public static string CollapseWhitespace(this string str)
{
if (str == null)
return null;
var sb = StringBuilderThreadStatic.Allocate();
var lastChar = (char)0;
for (var i = 0; i < str.Length; i++)
{
var c = str[i];
if (c < 32) continue; // Skip all these
if (c == 32)
{
if (lastChar == 32)
continue; // Only write one space character
}
sb.Append(c);
lastChar = c;
}
return StringBuilderThreadStatic.ReturnAndFree(sb);
}