我有一个字符数组,其中包含以下形式的电话号码:“(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/