Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Must be done in c#: Create a method that will accept a String as an argument and

ID: 3876223 • Letter: M

Question

Must be done in c#:

Create a method that will accept a String as an argument and then check to see if the String follows the pattern of a phone number (XXX) XXX-XXXX. In the main prompt the user for a phone number to check. You should validate that this is not left blank. Then send this string in to a custom method you create that will check that it is a valid phone number. You must check the following:

1. Only one ( symbol in the whole string and in the right position.

2. Only one ) symbol in the whole string and in the right position.

3. Only one - symbol in the whole string and in the right position.

4. Only one “ “ space symbol in the whole string and in the right position.

5. The length of the string should be checked to make sure it is correct.

6. The code should work for any string entered.

Explanation / Answer

using System;

class MainClass {
  
public static bool verifyPh(string ph)
{
// checking if the length is correct or not
if(ph.Length != 14)
return false;
  
// Checking if the symbols and space are correct or not
if(ph[0] != '(' || ph[4] != ')' || ph[5] != ' ' || ph[9] != '-')
return false;
  
// numbers should be in the indices of 1, 2, 3, 6, 7, 8, 10, 11, 12 and 13
if((ph[1] <= '0' || ph[1] >= '9') || (ph[2] <= '0' || ph[2] >= '9') || (ph[3] <= '0' || ph[3] >= '9') || (ph[6] <= '0' || ph[6] >= '9') || (ph[7] <= '0' || ph[7] >= '9') || (ph[8] <= '0' || ph[8] >= '9') || (ph[10] <= '0' || ph[10] >= '9') || (ph[11] <= '0' || ph[11] >= '9') || (ph[12] <= '0' || ph[12] >= '9') || (ph[13] <= '0' || ph[13] >= '9'))
return false;
  
// if all cases are passed, then returning true
return true;
}
public static void Main (string[] args) {
  
// taking user input
Console.Write("Enter a phone number: ");
string phn = Console.ReadLine();
char first = phn[0];
bool result = false;
  
// chekcing for first character if it is blank
if(first != ' ')
result = verifyPh(phn);
  
// printing output
if(result == false)
Console.WriteLine("Not a valid phone number.");
else
Console.WriteLine("Valid phone number.");
}
}

/*SAMPLE OUTPUTS
Enter a phone number: 123
Not a valid phone number.

Enter a phone number: (123) 123-1231
Valid phone number.

Enter a phone number: (123)123-1231
Not a valid phone number.
*/