The tasks in each exercise will be in bullet points, and each task will have its solution directly below it in a code block. Unless the solution highlights a new concept not yet covered in this series, this article will have less commentary for each task.
- Update your variable to ask the user for their social security number, store their input into a string variable
string message = "What is your social security number?"
string ss = Console.ReadLine();
Similar to the task in the previous article.
- Display only the first digits of their SSN
// remove non-number chars
Regex rgx = new Regex("[^0-9 -]");
string temp = rgx.Replace(ss, "");// check user input correct number of characters
if(temp.Length == 9)
ss = temp;
Console.WriteLIne("Please use 123-45-6789 format");
ss = Cosole.ReadLine();
}// display the first four digits of the ss number
First there needs to be some input validation, because the user may use the 123456789 format, the 123–45–6789 format, or the 123 45 6789 format. A regular expression will be able to handle whichever format the user chooses and transform it into a standard format. So if after removing non-numerical characters the string is not nine characters long, the input is not a valid SS number and the code will ask for the input again.
Notice the type declaration of the regular expression. It is of type
- Display only the last four digits of their SSN
This is similar to the previous task.
- Display the whole SSN removing all dashes and replacing all but the last four digits with the * symbol
Console.WriteLine("*****" + ss.Substring(5));
That is the second exercise from the worksheet. I hope this helps dispel any fears you may have of learning a new language. It was daunting for me from the outside, but once I actually started to look into the details of how it is written, C# got a whole lot more welcoming.
There will be one more exercise to work through before I refactor the code to be more object oriented.