完成下面的源代码,以构建一个按词典顺序打印出第一个字符串的程序

时间:2018-12-01 08:11:28

标签: c arrays pointers

这是问题。从字典顺序的角度比较两个字符串。>

我原本以为是错。

int main(void)
{
    char* pcolor[] = {"red", "orange", "yellow", "green", "blue",  "indigo", "violet", "purple", "white", "ivory", "gray", "black", "cyan", "pink", NULL};

    char* pt = pcolor[0], * pbegin = pcolor[0], * min = NULL, * temp = NULL;
    char min_c[2] = "1", pbegin_c[2] = "1";
    int i, j, k = 1, imin;

    for (pt = pcolor[0], i = 0; pt != NULL; pt = pt + strlen(pcolor[i++]) + 1)
    {
        printf("%s\n", pt);// == puts(pt);
    }

    for (i = 0; pt != NULL; i++)
    {
        pt = pcolor[i];
        imin = i;
        min = pt;

        for (j = i; pbegin != NULL; j++)
        {
            pbegin = pcolor[j];

            if (min == pbegin)
            {
                pbegin = pcolor[j++];
                continue;
            }

            strncpy(min_c, min, sizeof(min_c) - 1);
            strncpy(pbegin_c, pbegin, sizeof(pbegin_c) - 1);

            if (strcmp(min_c, pbegin_c) == 1)
            {
                min = pbegin;
                imin = j;
            }
            else if (strcmp(min_c, pbegin_c) == 0)
            {
                while (min+k != NULL || pbegin+k != NULL)
                {
                    strncpy(min_c, min+k, sizeof(min_c) - 1);
                    strncpy(pbegin_c, pbegin+k, sizeof(pbegin_c) - 1);

                    if (strcmp(min_c, pbegin_c) == 1)
                    {
                        min = pbegin;
                        imin = j;
                        break;
                    }

                    k++;
                }
            }

        }
        pcolor[i] = min;
        pcolor[imin] = pt;

    }
    for (i = 0; pcolor[i] != NULL; i++)
        puts(pcolor[i]);

    return 0;
}

0 个答案:

没有答案