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

标签 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 );
    }
}

我删除前导括号的方式感觉有点矫揉造作,但我不能只增加函数中的指针,因为调用版本的指针不会得到更新。我还觉得我可以在整个功能中总体上“更聪明”。

有什么想法/建议吗?

最佳答案

既然您声明您的输入保证采用正确的格式,那么以下内容如何:

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

memmove() 保证与重叠缓冲区一起工作

关于c - 需要更好的方法来格式化 C 中的电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1441100/

相关文章:

c - 用C编写命令行shell;第一次尝试使用 ncurses/C

c - 我不断收到“第一个函数中的线程 1 EXC_BAD_ACCESS 断点

android - 阻止 Android Studio 包装方法和构造函数

c++ - 包含许多 "if"的关键循环,其输出为常量 : How to save on condition tests?

c++ - 在 C++ 共享库的 header 中声明 'extern "C"' 有什么影响?

objective-c - Uncrustify:单行方法名称并删除双星号之间的空格

css - 无法获取自定义元素符号图像以显示列表项的右侧

c - C中的字符串格式化

c - GCC 中的 -D__USE_FIXED_PROTOTYPES__ 有什么用?

latex - 如何更改 Latex 中图形的标题?