在C中按字母顺序对单词进行排序 [英] sort words alphabeticaly in C

查看:1196
本文介绍了在C中按字母顺序对单词进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我的C语言程序必须找到N个字母的单词,对它们进行计数并按字典顺序对其进行排序,然后将其保存到另一个文件中.我该如何按字母顺序对单词进行排序?

I have a problem, my program in C have to find words with N letters, count them and sort them in lexicographical order and save them to an another file. How could I sort the words in alphabetical order?

这是我的代码:

#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <stddef.h>
#include <string.h>

int main()
{
FILE *r, *fp;
char ch[100],t[100];
int n,i,j,x=0;


r=fopen("text.txt","r");
fp=fopen("text2.txt","w");
fgets(ch, 100, r);


char *start;
int len;
char *s = ch;
char *p = s;
printf("Give the length of word: ");
scanf("%d",&n);
printf("\n\nWords with %d letters: \n\n",n);
    while (*p) {

        while (*p && isspace(*p))
            ++p;
        start = p; 

        while (*p && !isspace(*p))
            ++p;

        len = p - start;

        if (len == n) {

            printf("%.*s\n", len, start);
              x++;

            fprintf(fp,"%.*s",len, start);

        }    
    }      


printf("\nNumber of words: %d ",x);
fclose(fp);



getch();      
fclose(r);  
} 

推荐答案

有一个用于排序的标准库函数:

There's a standard library function for sorting:

https://en.wikipedia.org/wiki/Qsort

这篇关于在C中按字母顺序对单词进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆