给一个由n个单词组成的字符串排序

来源:互联网 发布:济宁淘宝代运 编辑:程序博客网 时间:2024/05/18 01:25

给一个由n个单词的组成的字符串排序,单词间由空格分隔。

如果字符串为b ab bc,则输出为ab b bc

思路:先将字符串分解成单词数组,然后排序,最后输出

代码如下:

#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX_N 100#define MAX_LEN 20int sortWords(char *s){    if (s == NULL) return 0;    char tmp[MAX_N][MAX_LEN];    int cnt = 0;    for (int i = 0; i < strlen(s); i++)    {        int j = i;        while (j < strlen(s))        {            if (s[j] == ' ') break;            j++;        }        strncpy(tmp[cnt], &s[i], j - i);        tmp[cnt][j - i] = 0;        cnt++;        i = j;    }    qsort(tmp, cnt, sizeof(tmp[0]), (int (*)(const void*,const void*))strcmp);    s[0] = 0;    for (int i = 0; i < cnt; i++)    {        strcat(s, tmp[i]);        if (i != cnt - 1) strcat(s, " ");    }    printf("result:%s\n", s);}int main(){    char s[MAX_N * MAX_LEN];    gets(s);    sortWords(s);    return 0;}


0 0