【问题标题】:How do I sort lastname by alphabetical order?如何按字母顺序对姓氏进行排序?
【发布时间】:2020-09-10 17:39:58
【问题描述】:

此程序仅用于按字母顺序排列名字。

我的代码

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

void main()
{
    char name[10][8], temp[8];
    int i, j, n;

    printf("Enter the value of n \n");
    scanf("%d", &n);
    for (i = 0; i < n; i++)
    {
        scanf("%s", name[i]);
    }
    for (i = 0; i < n - 1 ; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (strcmp(name[i], name[j]) > 0)
            {
                strcpy(temp, name[i]);
                strcpy(name[i], name[j]);
                strcpy(name[j], temp);
            }
        }
    }
    printf("Input name changes alphabetically\n");
    for (i = 0; i < n; i++)
    {
        printf("\t%s\n", name[i]);
    }
    return 0;
}

(程序的输出)

假设,输入

Enter the value of 2

  merge

  bubble

输出

Input name changes alphabetically 

  bubble

  merge

但我想编写这个程序来按字母顺序对 lastname 进行排序。

假设,例如

输入

Marop hossain

Nihan ahmed

输出

Nihan ahmed

Marop hossain

我是编程新手,所以我不懂。如何更改上面的代码以获得此结果。

【问题讨论】:

  • 如果你展示的代码是你写的就好了。:)

标签: c arrays string loops


【解决方案1】:

下面的代码应该可以正常工作

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

int main()
{
    char name[10][8], temp[8];
    int i, j, n,L,k;

    printf("Enter the value of n \n");
    scanf("%d", &n);
    fflush(stdin);

    for (i = 0; i < n; i++)
    {
        gets(name[i]);

    }

    for (i = 0; i < n - 1 ; i++)
    {    
        k=0;
        while(1)  //searches for the whitespace in the string
        {
            ++k;
            if(name[i][k]==' ') 
            break;

         }

        for (j = i + 1; j < n; j++)
        {

            L=0;
            while(1)
            {
                ++L;
                if(name[j][L]==' ')
                break;

            }
            if(name[i][k+1]>name[j][L+1]) //compares the char after the whitespace
            {
                strcpy(temp, name[i]);
                strcpy(name[i], name[j]);
                strcpy(name[j], temp);
            }

        }
    }
    printf("Input name changes alphabetically\n");
    for (i = 0; i < n; i++)
    {
        puts(name[i]);
    }
    return 0;
} ```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 2020-11-03
    • 2023-04-03
    • 2013-11-30
    • 1970-01-01
    • 2016-12-27
    相关资源
    最近更新 更多