在C中创建迭代数组和格式化电话号码的方法

在C中创建迭代数组和格式化电话号码的方法,c,arrays,printing,printf,C,Arrays,Printing,Printf,我是C语言编程新手,我正在编写一个简单的程序来接收用户输入(一个基本电话号码,即:(678)-653.7539),并以标准格式输出) 我采取的方法是首先去掉所有句点、连字符和括号 目前,该程序只打印数字,但我想要的格式是: (xxx)xxx xxxx 我正在考虑用数组创建一个方法,然后迭代(类似于堆栈?)使其输入“(在I[0]之前,在I[2]之后),依此类推 这是正确的方法吗 #include <stdio.h> void removeHyphen( char s[], char

我是C语言编程新手,我正在编写一个简单的程序来接收用户输入(一个基本电话号码,即:(678)-653.7539),并以标准格式输出)

我采取的方法是首先去掉所有句点、连字符和括号

目前,该程序只打印数字,但我想要的格式是:

(xxx)xxx xxxx

我正在考虑用数组创建一个方法,然后迭代(类似于堆栈?)使其输入“(在I[0]之前,在I[2]之后),依此类推

这是正确的方法吗

#include <stdio.h>

void removeHyphen( char s[], char x );
void removeLeftParen( char s[], char f );
void removeRightParen( char s[], char g );
void removePeriod( char s[], char h );

int main()
{
    char s[50];

    printf("Enter your phone number:\n");
    scanf("%s", s);

    printf( "Your phone number: %.13s\n", s );

    removeHyphen( s, '-' );
    removeLeftParen(s, '(');
    removeRightParen(s, ')');
    removePeriod(s, '.');

    printf( "Formatted phone number: %.10s\n", s );


    getchar();
    return 0;
}

void removeHyphen(char s[], char x)
{
    int i, j;
    for (i = 0 ; s[i] != 0 ; ++i)
    {
        while(s[i]==x)
        {
            j=i;
            while(s[j]!=0)
            {
                s[j]=s[j+1];
                ++j;
            }
        }
    }
}

void removeLeftParen(char s[], char f)
{
    int i, j;
    for (i = 0 ; s[i] != 0 ; ++i)
    {
        while(s[i]==f)
        {
            j=i;
            while(s[j]!=0)
            {
                s[j]=s[j+1];
                ++j;
            }
        }
    }
}

void removeRightParen(char s[], char g)
{
    int i, j;
    for (i = 0 ; s[i] != 0 ; ++i)
    {
        while(s[i]==g)
        {
            j=i;
            while(s[j]!=0)
            {
                s[j]=s[j+1];
                ++j;
            }
        }
    }
}

void removePeriod(char s[], char h)
{
    int i, j;
    for (i = 0 ; s[i] != 0 ; ++i)
    {
        while(s[i]==h)
        {
            j=i;
            while(s[j]!=0)
            {
                s[j]=s[j+1];
                ++j;
            }
        }
    }
}
#包括
无效删除连字符(字符s[],字符x);
无效清除权(字符s[],字符f);
去空洞剂(char s[],char g);
无效清除期(字符s[],字符h);
int main()
{
chars[50];
printf(“输入您的电话号码:\n”);
scanf(“%s”,s);
printf(“您的电话号码:%.13s\n”,s);
移除连字符(s,“-”);
去除血小板;
(s),;
移除周期;
printf(“格式化电话号码:%.10s\n”,s);
getchar();
返回0;
}
无效删除连字符(字符s[],字符x)
{
int i,j;
对于(i=0;s[i]!=0;++i)
{
而(s[i]==x)
{
j=i;
而(s[j]!=0)
{
s[j]=s[j+1];
++j;
}
}
}
}
void removereftparen(字符s[],字符f)
{
int i,j;
对于(i=0;s[i]!=0;++i)
{
而(s[i]==f)
{
j=i;
而(s[j]!=0)
{
s[j]=s[j+1];
++j;
}
}
}
}
无效清除器参数(字符s[],字符g)
{
int i,j;
对于(i=0;s[i]!=0;++i)
{
而(s[i]==g)
{
j=i;
而(s[j]!=0)
{
s[j]=s[j+1];
++j;
}
}
}
}
无效删除周期(字符s[],字符h)
{
int i,j;
对于(i=0;s[i]!=0;++i)
{
而(s[i]==h)
{
j=i;
而(s[j]!=0)
{
s[j]=s[j+1];
++j;
}
}
}
}

您可能不需要所有的删除逻辑。您只需迭代输入并复制数字字符即可

伪代码思想:

char output[50];   // better: char output[sizeof input];
                   // This is essentially processed/normalized input.
                   // In fact, since we know that it is a 10-digit
                   // phone number we can just do: char output[10];
                   // If you ever need to store the phone number for
                   // long term, the last option may be the best option.

const int n = actual length of input, e.g. strlen()
int j = 0;
for (int i = 0; i < n; ++i) {
  if (isdigit((unsigned char) input[i]) {
    output[j++] = input[i];
  }
}

// Validate 'output', for e.g. check that it has 10 characters

// Print output in desired format
char-output[50];//更好:char-output[sizeof-input];
//这基本上是经过处理/规范化的输入。
//事实上,因为我们知道它是一个10位数
//我们可以做的电话号码:字符输出[10];
//如果您需要为存储电话号码
//从长远来看,最后一个选择可能是最好的选择。
const int n=输入的实际长度,例如strlen()
int j=0;
对于(int i=0;i
有关详细信息,请参见手册第页


采用相同思想的不同程序结构如下所示。接受输入时,将其扫描为字符,忽略非数字字符。

删除所有不需要的字符后,可以执行此操作

void printFormatted(char *s)
{
    int i;
    if (s == NULL)
        return;
    fputc('(', stdout);
    for (i = 0 ; ((i < 3) && (s[i] != '\0')) ; ++i)
        fputc(s[i], stdout);
    fputc(')', stdout);
    fputc(' ', stdout);
    if (s[i] == '\0')
        return;
    for ( ; ((i < 6) && (s[i] != '\0')) ; ++i)
        fputc(s[i], stdout);
    fputc('-', stdout);
    if (s[i] == '\0')
        return;
    for ( ; s[i] != '\0' ; ++i)
        fputc(s[i], stdout);
    fputc('\n', stdout);
}
void打印格式(char*s)
{
int i;
如果(s==NULL)
返回;
fputc(“(”,stdout);
对于(i=0;((i<3)和&(s[i]!='\0');+i)
fputc(s[i],标准时间);
fputc('),stdout);
fputc(“”,标准输出);
如果(s[i]='\0')
返回;
对于(;((i<6)和&(s[i]!='\0');+i)
fputc(s[i],标准时间);
fputc('-',stdout);
如果(s[i]='\0')
返回;
对于(;s[i]!='\0';++i)
fputc(s[i],标准时间);
fputc('\n',stdout);
}
虽然如果您只是对程序的输出感兴趣,您实际上不需要删除任何内容,但是您可以使用它

#include <stdio.h>
#include <ctype.h>

void printFormatted(char *phone);

int main()
{
    char phone[50];

    printf("Enter your phone number: ");
    if (scanf("%49s%*c", phone) == 1)
    {
        printf( "Your input            : %s\n", phone);
        printf("Formatted phone number : ");
        printFormatted(phone);
        printf("\n");
    }

    return 0;
}

int putdigit(char digit)
{
    /* Print a charater if it's a digit (0-9) */
    if (isdigit((int)digit) == 0)
        return 0;
    fputc(digit, stdout);
    return 1;
}

void printFormatted(char *phone)
{
    int i;
    int j;
    /* Always be safe */
    if (phone == NULL)
        return;
    /* Output the `(' */
    fputc('(', stdout);
    /* Output 3 digits */
    for (i = 0, j = 0 ; ((j < 3) && (phone[i] != '\0')) ; ++i)
        j += putdigit(phone[i]);
    /* Output the `)' and a space */
    fputc(')', stdout);
    fputc(' ', stdout);
    /* Check if there are more characters */
    if (phone[i] == '\0')
        return;
    /* Output 3 digits */
    for (j = 0 ; ((j < 3) && (phone[i] != '\0')) ; ++i)
        j += putdigit(phone[i]);
    /* Output the hypen */
    fputc('-', stdout);
    /* Check if there are more characters */
    if (phone[i] == '\0')
        return;
    /* Output the rest of the characters */
    for ( ; phone[i] != '\0' ; ++i)
        putdigit(phone[i]);
    fputc('\n', stdout);
}
#包括
#包括
无效打印格式(字符*电话);
int main()
{
字符电话[50];
printf(“输入您的电话号码:”);
如果(扫描频率(“%49s%*c”,电话)==1)
{
printf(“您的输入:%s\n”,电话);
printf(“格式化电话号码:”);
打印格式(电话);
printf(“\n”);
}
返回0;
}
整数位(字符位)
{
/*如果是数字(0-9),则打印字符*/
如果(isdigit((int)位)==0)
返回0;
fputc(数字,标准输出);
返回1;
}
无效打印格式(字符*电话)
{
int i;
int j;
/*永远安全*/
如果(电话==NULL)
返回;
/*输出`('*/
fputc(“(”,stdout);
/*输出3位数字*/
对于(i=0,j=0;((j<3)和&(phone[i]!='\0');++i)
j+=putdigit(电话[i]);
/*输出“)”和空格*/
fputc('),stdout);
fputc(“”,标准输出);
/*检查是否有更多字符*/
如果(电话[i]='\0')
返回;
/*输出3位数字*/
对于(j=0;((j<3)和&(电话[i]!='\0');+i)
j+=putdigit(电话[i]);
/*输出催眠*/
fputc('-',stdout);
/*检查是否有更多字符*/
如果(电话[i]='\0')
返回;
/*输出其余字符*/
对于(;phone[i]!='\0';++i)
putdigit(电话[i]);
fputc('\n',stdout);
}

您确切地知道您的最终产品应该是什么样子的。它将是
char result[15]
。因此,一个简单的蛮力算法如下所示:

//set the known characters in the output string
result[ 0 ] = '(';
result[ 4 ] = ')';
result[ 5 ] = ' ';
result[ 9 ] = '-';
result[ 14 ] = '/0'; //null terminator

int index = 0;

//pseudocode
foreach( character in input )
    if character is a number 
        if index == 0, 4, 5, 9
            ++index;
        if index == 14 //we're out of room
            print result;
            exit;
        result[ index++ ] = character;
    else 
        ignore character

其中,“字符是一个数字”可能是您需要编写的唯一函数。

我建议使用
strtok

下面是一个例子

#include <stdio.h>
#include <string.h>

int main(void){
    char s[50], f[50];
    char *part[3] = { NULL };
    char *p;
    int i;

    printf("Enter your phone number:\n");
    scanf("%49s", s);

    printf( "Your phone number: %s\n", s );

    p = strtok(s, "-().");
    for(i=0; p!=NULL && i<3; ++i){
        part[i] = p;//Better to add one of the check is made up of numbers.
        p = strtok(NULL, "-().");
    }
    if(i==3){
        sprintf(f, "(%s) %s-%s", part[0], part[1], part[2]);
        printf( "Formatted phone number: %s\n", f );
    } else {
        printf("invalid format\n");
    }

    getchar();
    return 0;
}
#包括
#包括
内部主(空){
字符s[50],f[50];
字符*部分[3]={NULL};
char*p;
int i;
printf(“输入您的电话号码:\n”);
scanf(“%49s”,s);
printf(“您的电话号码:%s\n”,s);
p=strtok(s,“-()”);

对于(i=0;p!=NULL&&i另一种方法。构建字符串
#include <ctype.h>

// 0: success, 1 fail
int FormatPhoneNumber(const char *format, char *dest, const char *src) {
  int i;
  for (i = 0; format[i]; i++) {
    if (format[i] == 'x') {
      while (!isdigit((unsigned char) *src)) {
        if (*src++ == '\0') {
          dest[i] = '\0';
          return 1;  // fail, missing digit
        }
      }
      dest[i] = *src++;
    } else {
      dest[i] = format[i];
    }
  }
  dest[i] = '\0';
  while (*src && !isdigit((unsigned char) *src)) src++;
  return *src ? 1 : 0;
}

#include <stdio.h>

int main(void) {
  const char format[] = "(xxx) xxx-xxxx";
  char buf[sizeof format];
  int result = FormatPhoneNumber(format, buf, " (678)-653.7539),");
  printf("%d '%s'\n", result, buf);
  result = FormatPhoneNumber(format, buf, "Jenny: 111-867-5309");
  printf("%d '%s'\n", result, buf);
  return 0;
}