题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5af18ba2eb45443aa91a11e848aa6723
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int n; char **strs; char *str; unsigned int strCount=0; unsigned int bufferLen; scanf("%d",&n); strs = (char**)malloc(n*sizeof(char *)); bufferLen = n*10*sizeof(char); str = (char*)malloc(bufferLen); //存储数据 for(int i=0;i<n;i++) { char tempStr[101]; unsigned int tempStrCount=0; scanf("%100s",tempStr); tempStrCount=strlen(tempStr); if(strCount+tempStrCount+1>bufferLen) { bufferLen+=101; str=(char*)realloc(str,bufferLen);//使用realloc之后,之前的数据物理地址会变 } strcpy(str+strCount,tempStr); strCount+=tempStrCount+1;//还要加上\0占的1字节 } //查找字符串索引 for(int i=0;i<bufferLen;i++) { static int strsCount=0; static int tempStrCount = 0; if(str[i]=='\0') { if(strsCount==n) break; else{ strs[strsCount++]=str+i-tempStrCount; tempStrCount = 0; } } else tempStrCount++; } //冒泡排序 for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(strcmp(strs[j],strs[j+1])>0) { char* temp = strs[j]; strs[j]=strs[j+1]; strs[j+1]=temp; } } } for(int i=0;i<n;i++) { printf("%s\n",strs[i]); } free(strs); free(str); return 0; }