gpt4 book ai didi

C - 从字符串中解析电话号码

转载 作者:行者123 更新时间:2023-11-30 15:34:57 26 4
gpt4 key购买 nike

我正在尝试从文件中提取电话号码并将其打印出来

输入

my number is (123) 456-7897 ok, my other number is (654) 393-3030 buddy.

我的变量是

char *last_token;
char *firstpart;
char buffer[BUFFER_SIZE];
char *phoneNumber;

这是我当前的循环

while( fgets(buffer, BUFFER_SIZE, input) != NULL ){
last_token = strtok( buffer, " \n" );
while(last_token != NULL) {
//see if first part of number is correct
if(*last_token == '(' && isdigit(*(last_token + 1)) && isdigit(*(last_token + 2)) && isdigit(*(last_token + 3)) && *(last_token + 4) == ')' && *(last_token + 5) == '\0') {
firstpart = last_token; //if it is save it
last_token = strtok(NULL, " \n"); //check next part
//if second part is also correct
if (isdigit(*last_token) && isdigit(*(last_token + 1)) && isdigit(*(last_token + 2)) && *(last_token + 3) == '-' && isdigit(*(last_token + 4)) && isdigit(*(last_token + 5)) && isdigit(*(last_token + 6)) && isdigit(*(last_token + 7)) && *(last_token + 8) == '\0') {
phoneNumber = firstpart; //set phone number to first part
strcat(phoneNumber, " "); //add a space to phone number
strcat(phoneNumber, last_token); //add the last part of the phone nmber

printf("%s\n", phoneNumber); //print the number
}
}
last_token = strtok(NULL, " \n");
}

}

应该正在打印

(123) 456-7897
(654) 393-3030

而是打印它

(123)
(654)

我猜测字符串在 ) 之后被终止,但我不明白为什么

最佳答案

strcat(phoneNumber, " ");

这是用 '\0' 重写到 last_token 的开头。

char phoneNumber[15];
...
strcpy(phoneNumber, firstpart);
strcat(phoneNumber, " ");
strcat(phoneNumber, last_token);
printf("%s\n", phoneNumber);

关于C - 从字符串中解析电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23120760/

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