作业帮 > 综合 > 作业

C语言,单词排序,将一篇英语文章出现的单词去掉重复的,并按字母顺序排列

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/17 09:10:24
C语言,单词排序,将一篇英语文章出现的单词去掉重复的,并按字母顺序排列
如:Six hundred years ago,Sir Johan Hawkwood arrived in Italy with a band of soldiers and settled near Florence..
按字母顺序排列:
a ago and arrived band Florence Hawkwood hundred in Italy Johan near of settled Sir Six soldiers with years
注意大写字母开头的也要正确排序


#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
    char *b = "Six hundred years ago, Sir Johan Hawkwood arrived in Italy with a band of soldiers and settled near Florence.";
    char a[100][20] = {'\0'};
    char temp[20],temp1[20],temp2[20];
    int i, j, k;
    for (i=0,j=0,k=0; b[i]!='\0'; i++)
    {
        if(b[i] != ' '&& !ispunct(b[i]))
        {
            a[j][k] = b[i];
            k++;
        }
        else
        {
            j++;
            k=0;
        }
    }
    for (i=0; i<=j; i++)
    {
        for (k=i+1; k<=j; k++)
        {
            strcpy(temp1, a[i]);
            *temp1 = tolower(*temp1);
            strcpy(temp2, a[k]);
            *temp2 = tolower(*temp2);
            if (strcmp(temp1, temp2) == 1)
            {
                strcpy(temp, a[i]);
                strcpy(a[i], a[k]);
                strcpy(a[k], temp);
            }
            else if (strcmp(temp1, temp2) == 0)
            {
                a[k][0] = '\0';
                k++;
            }
        }
        if(a[i][0] != '\0')
            printf("%s ", a[i]);
    }
}