C# String Extension Methods

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.

11 Responses

  1. Steve says:

    You can call string.Substring without the second parameter to just specify the startIndex

  2. Luke Lowrey says:

    @Steve well that would have saved some time

  3. Benjii says:

    follow the above link, it stripped the regex from the comment

  4. Luke Lowrey says:

    Hey benjii,

    Added in the method but I am on the lookout for something a bit more complete. This one will miss things like  

  5. Adam says:

    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”

  6. 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”);

  7. Luke Lowrey says:

    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.

  8. Luke Lowrey says:

    @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 ;

  9. 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()?

  10. @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 !

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>