I pursued an according algorithm with an absolute best performance, the following class embodies the solution.
Any comment is welcome.
class TextCompressor
{
private const char Seperator = '\x20';
private StringBuilder builder;
public TextCompressor()
{
this.builder = new StringBuilder();
}
public string Compress(string str)
{
int offset = 0;
int end = str.Length - 1;
for (int i = 0; i < end; i++)
{
if (Char.IsWhiteSpace(str[i]))
{
if (i != offset)
{
if (str[i] == Seperator)
{
if (!Char.IsWhiteSpace(str[i + 1]))
{
i++;
continue;
}
builder.Append(str, offset, (i - offset) + 1);
}
else
{
builder.Append(str, offset, i - offset);
builder.Append(Seperator);
}
}
offset = i + 1;
}
}
if (offset != 0)
{
builder.Append(str, offset, str.Length - offset);
return Char.IsWhiteSpace(str[end]) ? Release().TrimEnd() : Release();
}
return Trim(str);
}
private static string Trim(string s)
{
return (s.Length != 0 && (Char.IsWhiteSpace(s[0]) || Char.IsWhiteSpace(s[s.Length - 1]))) ? s.Trim() : s;
}
private string Release()
{
string s = builder.ToString();
builder.Length = 0;
return s;
}
}
Compress
vs. Regex.Replace
.. using \s{2,}
String: " The quick brown fox jumps over the lazy dog. "
- 1.97017 * (10 times faster)
- 19.333874
String: "The quick brown fox jumps over the lazy dog."
- 0.485821 * (16 times faster)
- 8.049062
Separator
\$\endgroup\$