Ah extension methods… where would we be without them? Writing slightly more code to perform common functions that’s where! I am fairly sure everyone has their own set of string extensions so I though I’d share what I currently have then you guys can shoot it down and direct me to / yell at me something more useful. Everybody wins!
I am also experimenting with using Github’s Gist for my code samples (with help from a handy wordpress plugin). The idea is this makes it easier for me to update and you to clone, steal, comment, share etc. Let me know if it works.
You can call string.Substring without the second parameter to just specify the startIndex
@Steve well that would have saved some time
Hey Luke,
Found a simple HTML stripper here
http://aliraza.wordpress.com/2007/07/05/how-to-remove-html-tags-from-string-in-c/
public string Strip(string text)
{
return Regex.Replace(text, @””, string.Empty);
}
Could be worth adding
follow the above link, it stripped the regex from the comment
Hey benjii,
Added in the method but I am on the lookout for something a bit more complete. This one will miss things like
I’ve always preferred:
Regex.Replace(input, “<[^>]*>”, ” “);
It handles single tags, and doesn’t remove tag contents.
Example:
input: “<p>The <b>quick</b> <em>brown</em> fox<br /> jumps over the lazy dog</p>”
output: “The quick brown fox jumps over the lazy dog”
Using Take(“123456″, 4 , true) return “1234…” i.e., a string longer than count, longer than the original, and yet, truncated. It probably should be changed so that:
Take(“123456″, 4 , false) => “1234″
Take(“123456″, 4 , true) => “1…”
As for “Format”, I have one just like it, but I call mine “With”
“a string {0}”.With(“Blah”);
Hey james – I normally use take for making sure I dont get strings truncated exceptions in the db. I do like “With” instead of “Format” rolls off the tongue nicely.
@Adam – yeah thats a good point. I will update with that regex although I am on the lookout for something a little more complete that gets rid of stuff like & n b s p ;
The IsNullOrEmpty extension will throw an exception if the string is null, since it tries to do null.IsNullOrEmpty(). That’s why they defined String.IsNullOrEmpty as a static method.
If you know the string isn’t null, then IsEmpty() would be a useful extension. How about IsBlankOrEmpty()?
@Luke: You missed my point.
if you say
“123456″.Take(4,true), you get back a string which is 7 characters long — BOOM ! A string truncated exceptions in the db !