gpt4 book ai didi

创建方法以遍历数组并在 C 中格式化电话号码

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:51 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于创建方法以遍历数组并在 C 中格式化电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29778960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com