【问题标题】:Check if streets are the same or not in array检查街道是否相同或不在数组中
【发布时间】:2020-07-05 09:25:24
【问题描述】:

从文件中,我上传了带有出租车代码的街道。 每辆出租车都有几条出发的街道。

例如布拉德皮特 12345

例如布拉德皮特 33333

例如布拉德皮特 34567

我的任务是显示这 3 个示例仅是 1 街道的所有唯一地址。

我的代码:

(函数)driver(taxi,drives, i, &counter);

void driver(Taxi *taxi, char *drives, int i, int *counter)
{
    int yesNo=0;
    int j;

    for(j=0;j<i;j++)
    {
        if(strstr(taxi[j].drives, taxi[i].drives)==NULL)
            yesNo=1;
    }
    if(yesNo==0)
        ++*counter;

}

街道相同,但最后的数字不同。我的问题是,如何只存储唯一地址​​。

【问题讨论】:

标签: arrays c file


【解决方案1】:

您的代码将始终将 yesNo 设置为 1,因为您不会在循环中跳过元素 i,请尝试:

for(j=0;j<i;j++)
{
    if(j != i && strstr(taxi[j].drives, taxi[i].drives)==NULL)
        yesNo=1;
}

另外请注意,您的方法在“Brad Pitt & Angelina Jolie 33333”之类的情况下会失败,strtol 可以帮助解决这个问题,例如:

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

int main(void)
{
    const char *streets[] = {
        "Brad Pitt 12345",
        "Burt Reynolds 1234",
        "Brad Pitt & Angelina Jolie 33333",
        "Angelina Jolie & Brad Pitt 33333",
        "Brad Pitt 3456789"
    };
    int n = sizeof streets / sizeof *streets;
    const char *street = "Brad Pitt";
    size_t len = strlen(street);

    for (int i = 0; i < n; i++)
    {
        if (strncmp(streets[i], street, len) == 0)
        {
            char *ptr = NULL;

            strtol(streets[i] + len, &ptr, 10);
            if (*ptr == '\0')
            {
                puts(streets[i]);
            }
        }
    }
    return 0;
}

输出:

Brad Pitt 12345
Brad Pitt 3456789

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 1970-01-01
    • 2023-04-07
    • 2018-03-31
    • 1970-01-01
    相关资源
    最近更新 更多