I have a character array that contains a phone number of the form: "(xxx)xxx-xxxx xxxx" and need to convert it to something of the form: "xxx-xxx-xxxx" where I would just truncate the extension. My initial pass at the function looks like this:
static void formatPhoneNum( char *phoneNum ) {
unsigned int i;
int numNumbers = 0;
/* Change the closing parenthesis to a dash and truncate at 12 chars. */
for ( i = 0; i < strlen( phoneNum ); i++ ) {
if ( phoneNum[i] == ')' ) {
phoneNum[i] = '-';
}
else if ( i == 13 ) {
phoneNum[i] = '\0';
break;
}
else if ( isdigit( phoneNum[i] ) ) {
numNumbers++;
}
}
/* If the phone number is empty or not a full phone number,
* i.e. just parentheses and dashes, or not 10 numbers
* format it as an emtpy string. */
if ( numNumbers != 10 ) {
strcpy( phoneNum, "" );
}
else {
/* Remove the first parenthesis. */
strcpy( phoneNum, phoneNum + 1 );
}
}
It feels kinda hokey the way I'm removing the leading paren, but I can't just increment the pointer in the function as the calling version's pointer won't get updated. I also feel like I could be "more clever" in general all throughout the function.
Any ideas/pointers?