字符串排序1(指针数组,元素指针,行指针)(strcmp)

1.编写函数sortstr1(), 按字母序对字符串数组进行升序排序;

2.编写函数sortstr2(),按字母序对字符串数组进行升序排序;

3.main()函数中调用sortstr1()和sortstr2(),分别完成对各星期字符串、月份字符串的排序;

输出样例:

在这里给出相应的输出。例如:

Friday Monday Saturday Sunday Thursday Tuesday Wednesday 
April August December February January July June March May November October September 

#include <stdio.h>
#include <string.h>
#define STR_LEN  32

char week[7][STR_LEN] = { "Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday" };
char* months[12] = { "January", "February", "March", "April", "May", "June", "July", "August",
                    "September", "October", "November", "December" };


void  sortstr1(char (*p)[STR_LEN], int n)//实参为二维数组,形参为行指针
{
    int i, j;
    for (i = 0; i < 7 - 1; i++)
    {
        for (j = i + 1; j < 7; j++)
        {//进行升序排列
            if (strcmp(*(p + i), *(p + j)) > 0)//strcmp >0, 前者大于后者
            {
                char a[STR_LEN];//定义一个过渡数组
                strcpy(a, *(p + i));
                strcpy(*(p + i), *(p + j));
                strcpy(*(p + j), a);
            }//if
        }//for
    }//for

}//sortstrl

void  sortstr2(char *p[], int n)//实参为指针数组,形参为指针数组
{
    int i, j;
    for (i = 0; i < 12 - 1; i++)
    {
        for (j = i + 1; j < 12; j++)
        {//进行升序排列
            if (strcmp(p[i], p[j]) > 0)
            {
                char *t = p[i];
                p[i] = p[j];
                p[j] = t;
            }//if
        }//for
    }//for

}//sortstr2

int main()
{
    int i = 0;
    sortstr1(week, 7);
    for (i = 0; i < 7; i++) 
    {
        printf("%s ", week[i]);
    }//for

    printf("\n");
    sortstr2(months, 12);
    for (i = 0; i < 12; i++) 
    {
        printf("%s ", months[i]);
    }//for

}

注:strcmp函数为字符串比较函数,头文件为<string.h>两个字符串从首元素开始比较ASCII码,

返回值 >0 ,前者大于后者

返回值 =0 ,前者等于后者

返回值 <0 ,前者小于后者

上一篇:redis第一篇


下一篇:数据可视化 世界疫情地图