12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-04 20:35:23
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
C语言中可以使用库函数strcmp和qsort来对字符串进行排序。使用strcmp函数比较两个字符串的大小,然后使用qsort函数对字符串数组进行排序。#include <stdio.h>#include <strin
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
C语言中可以使用库函数strcmp
和qsort
来对字符串进行排序。
strcmp
函数比较两个字符串的大小,然后使用qsort
函数对字符串数组进行排序。#include <stdio.h>#include <string.h>#include <stdlib.h>int compare(const void *a, const void *b) {return strcmp(*(const char**)a, *(const char**)b);}int main() {char *strings[] = {"hello", "world", "apple", "banana"};int n = sizeof(strings) / sizeof(strings[0]);qsort(strings, n, sizeof(char*), compare);for (int i = 0; i < n; i++) {printf("%s\n", strings[i]);}return 0;}
这段代码会对字符串数组strings
进行排序,输出结果为:
applebananahelloworld
#include <stdio.h>#include <string.h>void sortStrings(char *strings[], int n) {for (int i = 0; i < n - 1; i++) {for (int j = i + 1; j < n; j++) {if (strcmp(strings[i], strings[j]) > 0) {char *temp = strings[i];strings[i] = strings[j];strings[j] = temp;}}}}int main() {char *strings[] = {"hello", "world", "apple", "banana"};int n = sizeof(strings) / sizeof(strings[0]);sortStrings(strings, n);for (int i = 0; i < n; i++) {printf("%s\n", strings[i]);}return 0;}
这段代码会对字符串数组strings
进行排序,输出结果为:
applebananahelloworld
无论是使用qsort
函数还是自定义排序函数,都可以对字符串数组进行排序。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19