struct word {
int seqNum;
int len; // 单词长度
char *name;
};
struct word words[100001];
int cmp(const void *a, const void *b) {
struct word *aa =(struct word *)a;
struct word *bb = (struct word *)b;
if (aa->len != bb->len) {
return aa->len - bb->len;
} else {
return aa->seqNum - bb->seqNum;
}
return 0;
}
char * arrangeWords(char * text){
// printf("%d", sizeof(struct word));
memset(words, 0, sizeof(struct word) * 100000);
char *sep = " ";
//首字母转小写,不能直接转化, 要赋值一次
text[0] = tolower(text[0]);
char *token = NULL;
/* 获取第一个子字符串, 使用空格分割 */
token = strtok(text, sep);
int cnt = 0;
while(token != NULL) {
// printf("token: %s", token);
words[cnt].seqNum = cnt;
words[cnt].len = strlen(token);
words[cnt].name = (char *)malloc(sizeof(char) *(words[cnt].len + 1));
memset(words[cnt].name, 0 , sizeof(char) * (words[cnt].len + 1));
strcpy(words[cnt].name, token);
cnt++;
token = strtok(NULL, sep);
}
qsort(words, cnt, sizeof(struct word), cmp);
memset(text, 0, sizeof(char) * strlen(text));
for(int i = 0; i < cnt; i++) {
strcat(text, words[i].name);
if (i < cnt -1) {
strcat(text, sep);
}
}
text[0] = toupper(text[0]);
for(int i = 0; i < cnt; i++) {
free(words[i].name);
words[i].name = NULL;
}
return text;
}
1451. 重新排列句子中的单词【strtok,qsort,strcat,tolower,toupper, malloc】
最新推荐文章于 2024-07-10 16:47:58 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)