How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL’s like Stack Overflow?
For example how can I convert:
How do I generate a Friendly URL in C#?
Into
how-do-i-generate-a-friendly-url-in-C
There are several things that could be improved in Jeff’s solution, though.
IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don’t react at all.
Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue.
Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one.
Off the top of my head, without any testing whatsoever, this would be an equivalent solution:
Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.