我想将一个 10 位数的电话号码(例如:1112223333)转换成 3 组:
第 1 组将是:111
第 2 组:222
和第 3 组:3333
然后我想加入组来创建一个字符串,如:(111)-222-3333
我搜索了很多,但只找到了如何除以 10 来获取每个数字,或者如何使用我没有的分隔符进行拆分。
你能告诉我如何将电话号码拆分成多个部分吗?
编辑: 我有这样的事情:
void convert_phone(char *phone) {
if (strlen(phone) != 10) return 0;
int num;
int i = strlen(phone) - 1;
int array[strlen(phone)];
while (num > 0) {
array[i--] = num % 10;
num /= 10;
printf("%d\n", num);
}
return 1;
}
最佳答案
#include <stdio.h>
#include <string.h>
int convert_phone(char *outbuff, const char *phone){
if (strlen(phone) != 10) return 0;
char gp1[3+1] = {0};
char gp2[3+1] = {0};
char gp3[4+1] = {0};
strncpy(gp1, phone, 3);
strncpy(gp2, phone + 3, 3);
strncpy(gp3, phone + 6, 4);
sprintf(outbuff, "(%s)-%s-%s", gp1, gp2, gp3);
return 1;
}
int main(void){
const char *phone_num = "1112223333";
char buff[sizeof("(XXX)-XXX-XXXX")];
if(convert_phone(buff, phone_num))
printf("%s\n", buff);//(111)-222-3333
return 0;
}
关于c - 如何将一个 10 位数的电话号码分成几组数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17920123/