Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String formating in C# 1

Status
Not open for further replies.

palovidiu

Programmer
Nov 30, 2005
14
0
0
RO

I tried and search for a sample or some good
explanation on how could I format a string like
"12023023023023020302" (24 chars long)

I cannot use o NumberFormatInfo , and convert
the string above cause it's to f... long...

and string.Format("{0:###-####-#-####### ....}", someStringObject);

leaves the input string unchanged

thank you
 
palovidiu,

1. I used the same number you did, and even added some numbers onto the end. It wasn't too long to convert it to a double. I didn't try for a 32 or 64 bit int or even a long or a decimal, so converting shouldn't be a problem.

2. So, if you wanted to, you could do:
Convert.ToDouble("12023023023023020302").ToString("##-##-..");. Though, this didn't exactly work the way I wanted it to.

3. If you want to break from the string.format stuff, you could do a loop and split it wherever you would like for example:
Code:
string test = "1234567890";

int CharPos=0;
StringBuilder sb = new StringBuilder();
foreach (char c in test){
   CharPos++;
   switch (CharPos){
      case(1):case(2):case(3):
         sb.Append(c);
         break;
      case(4):
         sb.Append('-');
         sb.Append(c);
         break;
      default:
         sb.Append(c);
   }
   MessageBox.Show(sb.ToString());
}
OR
You could use regular expressions, and I would not be the right person to help you there...I have only a cursory knowledge of RegEx.

Of course #3 would require that you know the length of each string you want to format.

Good luck,
Kevin

- "The truth hurts, maybe not as much as jumping on a bicycle with no seat, but it hurts.
 
thanks for replying kmfna,

workarounds, I can think of many, I thought maybe I am
missing something regarding all this string formatting
stuff.
I know regex good enough but that would be .. overkill.
I did what I needed with substring and concatenation but
I was looking for an already made elegant solution.
(not writing my own IFormatProvider class)

thanks again for replying
 
I'd use a regex
_output = Regex.Replace(_input,@"(\d{3})(\d{4})(\d{1})(\d*)","$1-$2-$3-$4");
Marty
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top