views:

21

answers:

1

I've been using this class for a while now to cleans data into such a form that I can use it in my URL's and I was wondering if there's a faster/better way?

The order of the replacements is important as it ensures that theres no slashes at the beginning on completion and theres no double slashes in side of the text.

/// <summary>
/// Cleanses String for URL
/// </summary>
/// <param name="s">string</param>
/// <returns>URL Friendly String</returns>
public static string Clean(this string s)
{
    var sb = new StringBuilder(s.Trim());
    sb.Replace("&rsquo;", "");
    sb.Replace("-", " ");
    sb.Replace("/", "");
    sb.Replace("&", "and");
    sb.Replace(",", "");
    sb.Replace("  ", " ");
    sb.Replace(" ", "-");
    sb.Replace("'", "");
    sb.Replace(".", "");
    sb.Replace("eacute;", "e");
    sb.Replace("--", "-");

    if (sb[0].ToString() == "-") { sb[0].ToString().Replace("-", ""); }

    return sb.ToString().ToLower();
}

Thanks.

+1  A: 

It might not look pretty, but I think what you've got here is fine in terms of readability. One alternative would be to break this down into a few Regex replace statements, but then as always with regular expressions, the readability goes out the window.

Another alternative would be to build a list of the matches and their replacements, but I think this is going to end up making the code longer in the end.

Jeff Schumacher
is it better as it is or maybe as Oleg seems to be suggesting, daisy chaining all of the dots ala; return sb.replace("x","y").replace("c","d") which i thought was against best practice
Chris M
With chaining, you're just accessing a returned reference to the string builder object, which is fine, but it's not going to give you any gains in performance. Readability wise, chaining isn't going to look any worse/better than what you already have. It's a style choice at that point.
Jeff Schumacher