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

时间:2015-04-21 17:16:27

标签: c arrays printing printf

我是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;
            }
        }
    }
}

5 个答案:

答案 0 :(得分:1)

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

伪代码的想法:

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

请参阅isdigit()的手册页。

采用相同构思的不同程序结构如下。在接受输入时,将它们扫描为字符并忽略非数字字符。

答案 1 :(得分:1)

您确切知道您的最终产品应该是什么样子。它将是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

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

答案 2 :(得分:0)

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

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

如果你只是对程序的输出感兴趣,你真的不需要删除任何东西,你可以使用这个

#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);
}

答案 3 :(得分:0)

我建议使用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;
}

答案 4 :(得分:0)

另一种方法。按解释格式构建字符串。

#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;
}
  

0'(678)653-7539'
  0'(111)867-5309'