views:

878

answers:

3

I'm wondering if it's possible for .Net's String.Format() to split an integer apart into two sub strings. For example I have a number 3234 and I want to format it as 32X34. My integer will always have 4 or 6 digits. Is this possible using String.Format()? If so what format string would work?

P.S. I know there is other ways to do this, but i'm specifically interested to know if String.Format() can handle this.

A: 

No, it can't.

In fact, it seems that your integers aren't integers. Perhaps they should be stored in a class, with its own ToString() method that will format them this way.

John Saunders
Gah, at least try it once before posting.
Samuel
Try what? I've done the ToString override, and it works. I've never done a format string like that below, nor ever seen one.
John Saunders
+11  A: 

You can specify your own format when calling String.Format

String.Format("{0:00x00}", 2398) // = "23x93"
Samuel
+1 let me give that shot.
James
Works like a charm for the four digit numbers. I'll probably end up using a variation of Jeff's solution for the 4 and 6 digit condition but you get the question points for coming up with the hard part.
James
Why did I never try this before...I was doing substring() Thanks! :)
Adam Neal
+4  A: 

James, I'm not sure you've completely specified the problem.

If your goal is to put the 'x' in the center of the string, Samuel's answer won't work for 6 digit numbers. String.Format("{0:00x00}", 239851) returns "2398x51" instead of "239x851"

Instead, try:

String.Format(val<10000 ? "{0:00x00}" : "{0:000x000}", val)

In either case, the method is called Composite Formatting.

(I'm assuming the numbers will be between 1000 and 999999 inclusive. Even then, numbers between 1000 and 1009 inclusive will report the number after the 'x' with an unnecessary leading '0'. So maybe this approach is valid for values between 1010 and 999999 inclusive.)

JeffH
That's assuming he wants 123x456 instead of 1234x56.
Samuel
And this is why I suggested a class. He may be storing the data in an integer, but it does not have the semantics of an integer.
John Saunders
+1 i'll be using a variation of your solution for the 4 and 6 digit condition.
James