Formatting strings
November 15, 2006 5:36 AM   Subscribe

String manipulation in C#: I know that the String.Format method can format numeric data so that {0:#,###} transforms 1234 into the string "1,234". There are lots of standard formatters like {0:C} for currency, and endless ways to format DateTime objects. But is there a similar shorthand to format a string or to apply a mask to it?

I have a db table that contains ISBN values (look at the bar code on any book and you will see the value I am talking about). It is stored in the db as a char(10), since by definition an ISBN-10 is always 10 characters. But the formatting of an isbn is always n-nnn-nnnnn-n. The final character is sometimes a letter, so just using {0:#-###-#####-#} to format the display will not work. I know I can parse it out by using substrings ("{0}-{1}-{2}-{3}", value.Substring(0,1), value.Substring(1,3), etc.), but that seems awfully verbose. Is there a shorthand method that I am missing?
posted by Lokheed to Computers & Internet (3 answers total)
 
{0:#-###-#####-*}?
posted by pjern at 6:26 AM on November 15, 2006


Best answer: The real way to do this is to represent your ISBN value as a class and override the ToString method for it. At that point you should also be able to creat IFormatProvider objects to allow more flexible formatting.
posted by plinth at 6:29 AM on November 15, 2006 [1 favorite]


Response by poster: *thunk*

Of course. I should have thought of that, thanks. Much cleaner.
posted by Lokheed at 7:04 AM on November 15, 2006


« Older How long to detox from Medication Overuse Headache...   |   So what's the deal with Britney Spears's breasts? Newer »
This thread is closed to new comments.