I have a string similar to "foo-bar----baz--biz"
What is the easiest and fastest way to eliminate the insignificant duplicate characters(-
) and make the string "foo-bar-baz-biz"?
I've tried doing something like .Replace("--","-")
, but that appears to only work somewhat.. I'd have to run it in a loop to do it fully, and I know there is a better way.
What's the best way?
Try this,
string finalStr = string.Join("-", x.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries))
much better if this is transformed into Extension method
static class StringExtensions
{
public static string RemoveExtraHypen(this string str)
{
return string.Join("-", str.Split(new []{'-'}, StringSplitOptions.RemoveEmptyEntries));
}
}
usage
private void SampleDemo()
{
string x = "foo-bar----baz--biz";
Console.WriteLine(x.RemoveExtraHypen());
}
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