Skip to content

Instantly share code, notes, and snippets.

@squgeim
Created September 14, 2018 04:33
Show Gist options
  • Save squgeim/5fff1e9d9472171f85fb184fabb4a064 to your computer and use it in GitHub Desktop.
Save squgeim/5fff1e9d9472171f85fb184fabb4a064 to your computer and use it in GitHub Desktop.
Check whether an input string matches the pattern provided, in this case US phone number: (###) ###-#### where # is a number.
#include<stdio.h>
#include<string.h>
#define TRUE 1
#define FALSE 0
#define ZERO '0'
#define NINE '9'
#define TOTAL_LENGTH 14
// Types
#define PARA_START 0
#define PARA_END 1
#define NUMBER 2
#define DASH 3
#define SPACE 4
int is_phone_number(char *number) {
int i;
int len;
int position_type[TOTAL_LENGTH] = {
PARA_START,
NUMBER,
NUMBER,
NUMBER,
PARA_END,
SPACE,
NUMBER,
NUMBER,
NUMBER,
DASH,
NUMBER,
NUMBER,
NUMBER,
NUMBER
};
len = strlen(number);
if (len != TOTAL_LENGTH) {
return FALSE;
}
for (i = 0; i < len; i++) {
switch (position_type[i]) {
case PARA_START:
if (number[i] != '(') {
return FALSE;
}
break;
case PARA_END:
if (number[i] != ')') {
return FALSE;
}
break;
case DASH:
if (number[i] != '-') {
return FALSE;
}
break;
case SPACE:
if (number[i] != ' ') {
return FALSE;
}
break;
case NUMBER:
if (number[i] < ZERO || number[i] > NINE) {
return FALSE;
}
break;
}
}
return TRUE;
}
int main(int argc, char **argv) {
int is_phone = is_phone_number(argv[1]);
if (is_phone) {
printf("The given number is a phone number.\n");
} else {
printf("The given number is not a phone number.\n");
}
}
@squgeim
Copy link
Author

squgeim commented Sep 14, 2018

Check whether an input string matches the pattern provided, in this case US phone number: (###) ###-#### where # is a number.
Example:
(800) 123-4567 => true
(123) 000-0000 => true
(ABC) 123-AB12 => false
12345678 => false
ABC-123-123C => false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment