2015-12-09 99 views
1

这是常见的任务使用qtsort()排序整数数组,但它是可能的排序排序字符串数组让说数组排序

{"One","two","three","all"} or even take it higher sort "string number"? e.g 
{"50.5>ahoh","45>Two","50>here"} 

或者,我们仅限于分类型数组?

+1

什么是qtsort? – immibis

+1

在C中char是ASCII表中的一个数字。字符串是一个char数组。所以你可以排序字符串。使用'qsort()'函数,您必须传递参数的'compare'函数可以是'strcmp'。 – ViniciusArruda

+0

编写比较函数,如预期的行为。 – BLUEPIXY

回答

4

这是可能的字符串数组字典顺序,如果你使用了一个strcmp下面的自定义比较排序:

int cmpfunc(void *a, void *b) { 
    const char **ia = (const char **)a; 
    const char **ib = (const char **)b; 
    return strcmp(*ia, *ib); 
} 

int main() { 
    int n; 
    char *values[] = { "88", "56", "100", "2", "25" }; 

    printf("Before sorting the list is: \n"); 
    for(n = 0 ; n < 5; n++) 
    { 
     printf("%s ", values[n]); 
    } 

    qsort(values, 5, sizeof(char*), cmpfunc); 

    printf("\nAfter sorting the list is: \n"); 
    for(n = 0 ; n < 5; n++) 
    { 
     printf("%s ", values[n]); 
    } 

    return(0); 
} 

Live Demo

另外,如果你想有一个自定义的排序,你可以在定义与自定义比较器相同的方式来相应地比较输入字符串。

+0

可以“整数”吗?这是按第一个字符串编号排序的,而不是整个编号 – user3706129