需要更好的方法来格式化C中的电话号码

Mor*_*nar 2 c formatting

我有一个字符数组,其中包含以下形式的电话号码:"(xxx)xxx-xxxx xxxx"并需要将其转换为以下格式:"xxx-xxx-xxxx",我只是截断扩展名.我在函数的初始传递看起来像这样:

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 );
    }
}
Run Code Online (Sandbox Code Playgroud)

感觉有点像我正在删除领先的paren,但我不能只是增加函数中的指针,因为调用版本的指针不会更新.在整个功能中,我也觉得自己可以"更聪明".

任何想法/指针?

moc*_*ocj 6

由于您声明您的输入保证格式正确,因此以下内容如下:

static void formatPhoneNum( char *phoneNum )
{
    memmove(phoneNum, phoneNum + 1, 12);
    phoneNum[3]  = '-';
    phoneNum[12] = 0;
}
Run Code Online (Sandbox Code Playgroud)

memmove()保证与重叠缓冲区一起使用