C语言及程序设计提高例程-37 操作字符串数组

贺老师教学链接  C语言及程序设计提高 本课讲解


例:求最小姓氏

#include <stdio.h>
#include <string.h>
char *min_name(char [][10], int);
int main( )
{
    char name[5][10]= {"Zhao", "Qian", "Sun", "Li", "Zhou"};;
    printf("%s\n", min_name(name, 5)); 
    return 0;
}
char *min_name(char nam[][10], int n)
{
    int i;
    char *p;
    p = nam[0];
    for(i=0; i<n; i++)
        if(strcmp(p, nam[i])>0)
            p = nam[i];
    return p;
}


例:姓氏排序
#include <stdio.h>
#include <string.h>
void sort(char *name[],int n);
void print(char *name[],int n);
int main( )
{
    char *name[]= {"Zhao", "Qian", "Sun", "Li", "Zhou"};
    sort(name, 5);
    print(name, 5);
    return 0;
}
void print(char *name[],int n)
{
    int i;
    for(i=0; i<n; i++)
        printf("%s\n", name[i]);
}
void sort(char *name[],int n)
{
    char *temp;
    int i,j,k;
    for(i=0; i<n-1; i++)
    {
        k=i;
        for(j=i+1; j<n; j++)
            if(strcmp(name[k],name[j])>0)
                k=j;
        temp=name[i];
        name[i]=name[k];
        name[k]=temp;
    }
}


用二级指针处理
#include <stdio.h>
int main( )
{
    char **p;
    char *name[]= {"Zhao", "Qian", "Sun", "Li", "Zhou"};
    for(p=name+1; p<name+5; p+=2)
        printf("%s\n",*p);
    return 0;
}


你可能感兴趣的:(C语言及程序设计提高例程-37 操作字符串数组)