题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/dfeed0e0e4624814b122265e859783b2
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 1000 int compare(const void* a, const void* b) { const char* A = (const char*)a; const char* B = (const char*)b; int len1 = strlen(A); int len2 = strlen(B); return len1 - len2; } int main() { int n; scanf("%d", &n); char data[n][MAX]; getchar(); // 消耗掉输入缓冲区中的换行符 for (int i = 0; i < n; i++) { fgets(data[i], MAX, stdin); data[i][strcspn(data[i], "\n")] = '\0'; // 去除换行符 if(strcmp(data[i],"stop")==0) { n=i; break; } } // 使用qsort函数对字符串数组按照字符串长度进行排序 qsort(data, n, sizeof(data[0]), compare); for (int i = 0; i < n; i++) { printf("%s\n", data[i]); } return 0; }