I have Googled and looked and looked. What is the best cleanest way to format a social security number to look like xxx-xx-xxxx?

And as long as I am asking, how about how to ensure that a nine digit number is entered?

Thank you!

7 Years
Discussion Span
Last Post by spdesigns

Hello AbelLazm, Its just me again with the taxpayer code I am working on. US SSN so dashes after 3rd and 5th number in series. Has to be entered as a string.

//  Implement a for-loop that will prompt the user to enter the Social Security Number and gross income.
                for (x = 1; x < taxArray.Length; ++x)
                    taxArray[x] = new Taxpayer();
                    Console.Write("Please enter the Social Security Number for taxpayer {0}, (format as xxx-xx-xxx):  ", x);
                    taxArray[x].SSN = Console.ReadLine();

try this code

String s="";
            bool flag = true;
            while (flag)
                Console.WriteLine("Enter the string");
                s = Console.ReadLine();
                if (s.Length != 9)
                    Console.WriteLine("Wrong Input String must have 9 charachters Enter again");
                else flag = false;

            //Format according to xxx-xx-xxxx
            s = String.Format("{0}-{1}-{2}", s.Substring(0, 3), s.Substring(3, 2), s.Substring(5, 4));

Edited by abelLazm: n/a

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
    public partial class Form1 : Form
        public Form1()
            textBox1.MaxLength = 11;
            textBox1.TextAlign = HorizontalAlignment.Center;

        private void textBox1_TextChanged(object sender, EventArgs e)
                if (textBox1.Text.Length == 3)
                    textBox1.Text += '-';
                    textBox1.SelectionStart = 5;
                if (textBox1.Text.Length == 6)
                    textBox1.Text += '-';
                    textBox1.SelectionStart = 8;


Edited by Reverend Jim: Fixed formatting

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.