This piece of code works good. I have not measure the performance.
string text = " hello - world, here we go !!! a bc ";
string.Join(" ", text.Split().Where(x => x != ""));
// Output
// "hello - world, here we go !!! a bc"
accept characters from looping over the original string, as Blindy suggests
Here's the best balance of performance & readability I've found (using 100,000 iteration timing runs). Sometimes this tests faster than a less-legible version, at most 5% slower. On my small test string, regex takes 4.24x as much time.
public static string RemoveExtraWhitespace(string str)
{
var sb = new StringBuilder();
var prevIsWhitespace = false;
foreach (var ch in str)
{
var isWhitespace = char.IsWhiteSpace(ch);
if (prevIsWhitespace && isWhitespace)
{
continue;
}
sb.Append(ch);
prevIsWhitespace = isWhitespace;
}
return sb.ToString();
}
This piece of code works good. I have not measure the performance.
try this:
For those who just want to copy-pase and go on:
It's very simple, just use the
.Replace()
method:I've tried using StringBuilder to:
Here's the best balance of performance & readability I've found (using 100,000 iteration timing runs). Sometimes this tests faster than a less-legible version, at most 5% slower. On my small test string, regex takes 4.24x as much time.
There is no need for complex code! Here is a simple code that will remove any duplicates: