如何实现按指定的字母序进行排序

来源:互联网 发布:保定网络主播招聘 编辑:程序博客网 时间:2024/05/22 16:57

问题:

要求对用户输入的字符串中的单词按照指定的字母序进行排序,然后把排序后的字母依次输出。

分析:

使用字符串数组保存字符串中的单词,使用单独的字符串WORDORDER保存26个字母(按照指定的顺序保存)。每次比较数组中的两个字符串,从第一个字母开始比较(以字母在WORDORDER中的位置为比较依据,位置靠前的字母比靠后的字母大,不区分大小写),如果第一个字母相同,则比较第二个字母,依此类推。比较后交换指针,采用冒泡法进行排序。

 

头文件:

#include <stdio.h>
#include <string.h>
#include <malloc.h>


char WORDORDER[] = "BCDEFGHIJKLMNOPQRSTUVWXYZAbcdefghijklmnopqrstuvwxyza";
char seps[]   = " ,/t/n";

#define MAXWORDS 1000
#define MAXWORDLEN 20

typedef char* words;
words* wordArray;
int arraySize;
int wordSize;

#define SUCCESS 0
#define ERROR -1

main文件:

#include "wordSort.h"

//根据分隔符拆分字符串
int splitStr(char *str)
{
    int i = 0;
    char *token = strtok(str, seps);
    wordArray = (char**)malloc(sizeof(char*)*MAXWORDS);

    while(NULL != token)
    {
        printf("/ntoken=[%s]/n", token);
        wordArray[i] = (char*)malloc(sizeof(token)+1);
        memset(wordArray[i], 0, MAXWORDLEN);
        strcpy(wordArray[i],token);
        i++;
        token = strtok(NULL, seps);
    }
    arraySize = i;
    return SUCCESS;
}

//返回字符串中字符的位置
int cmpStr(char *str, char c)
{
    //如果要忽略大小写,就c|0x20得到小写来比较
    //if (c >= 0x41 && c < 0x61)
    //{
    //    c = c|0x20
    //}
    char *tmp = strchr(str,c);
    if (NULL == tmp)
    {
        return -1;
    }
    return (tmp-str)/sizeof(char);
}

//根据自定义的字母序比较两个字符串的大小
int compareStr(char *str1, char *str2)
{
    int result = 0;
    int i = 0;
    int length = (strlen(str1) > strlen(str2)) ? strlen(str2):strlen(str1);
    while (0 == result && i < length)
    {
        if (cmpStr(WORDORDER, str1[i]) > cmpStr(WORDORDER, str2[i]))
        {
            result = 1;
        }
        else if (cmpStr(WORDORDER, str1[i]) < cmpStr(WORDORDER, str2[i]))
        {
            result = -1;
        }
        else
        {
            result = 0;
        }
        i++;
    }
    //如果前面的字母都相同,就比较字符串的长度
    if (0 == result)
    {
        if (strlen(str1) > strlen(str2))
        {
            result = 1;
        }
        else if (strlen(str1) < strlen(str2))
        {
            result = -1;
        }
    }
    return result;
}

//交换字符串,把小的字符串放在前面
int switchStr(char **str1, char **str2)
{
    char *tmp;
    tmp = *str1;
    if (compareStr(*str1, *str2) > 0)
    {
        *str1 = *str2;
        *str2 = tmp;
    }
    //小于和等于的情况不交换
    return SUCCESS;
}

int sort(words *words)
{
    int i,j;
    for (i=0; i < arraySize; i++)
    {
        for (j = i+1; j<arraySize; j++)
        {
            switchStr((words+i),(words+j));
        }
    }
    return SUCCESS;
}

int main()
{
    int i;
    char str[] = "Chapter includes a smorgasbord of extensions and tools around Lucene";
    printf("%s", str);
   

    splitStr(str);
    sort(wordArray);
    for(i=0; i<arraySize; i++)
    {
        printf("%s ", *(wordArray+i));
    }
    gets(str);
}