qsort字符串排序
时间: 2023-12-04 10:37:38 浏览: 36
好的,关于qsort字符串排序,你可以使用qsort函数和strcmp函数来实现。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
char *strs[] = {"hello", "world", "apple", "banana", "orange"};
int len = sizeof(strs) / sizeof(char *);
qsort(strs, len, sizeof(char *), cmp);
for (int i = 0; i < len; i++) {
printf("%s ", strs[i]);
}
printf("\n");
return 0;
}
```
这个程序会输出:apple banana hello orange world
在这个程序中,我们定义了一个字符串数组,然后使用qsort函数对它进行排序。cmp函数是用来比较两个字符串的大小的,它会被qsort函数调用。在cmp函数中,我们使用了strcmp函数来比较两个字符串的大小。
相关问题
qsort函数字符串排序
以下是使用qsort函数对字符串进行排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp_string(const void* elem1, const void* elem2) {
return strcmp(*(char**)elem1, *(char**)elem2);
}
int main() {
char* arr[] = {"banana", "apple", "orange", "grape"};
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
qsort(arr, sz, sizeof(arr[0]), cmp_string);
for (i = 0; i < sz; i++) {
printf("%s ", arr[i]);
}
return 0;
}
```
输出结果为:apple banana grape orange
qsort排序字符串
您好!要使用qsort函数对字符串进行排序,您需要编写一个比较函数来指示排序的规则。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void* a, const void* b)
{
const char* str1 = *(const char**)a;
const char* str2 = *(const char**)b;
return strcmp(str1, str2);
}
int main()
{
char* strings[] = {"orange", "apple", "banana", "pear"};
int numStrings = sizeof(strings) / sizeof(strings[0]);
qsort(strings, numStrings, sizeof(char*), compare);
printf("排序后的字符串:\n");
for (int i = 0; i < numStrings; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
```
在这个例子中,我们使用qsort函数对字符串数组`strings`进行排序。比较函数`compare`使用strcmp函数来比较两个字符串的大小关系。最后,我们通过循环打印排序后的字符串数组。
希望这个例子能满足您的需求!如果有任何疑问,请随时提问。