2015-11-07 189 views
1

我有一個問題,我的程序在C中必須找到帶有N個字母的單詞,並按字典順序對它們進行計數並將它們保存到另一個文件中。我怎樣才能按字母順序排列單詞?排序字母在C中的排序

這是我的代碼:

#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); 
} 
+1

實現您自己的排序函數 – AkaSh

回答

0

可以很容易地編寫一個函數來排序的話alphabeticly它是非常相似的排序字母字符來對您在數組上迭代的字符進行排序,並且一次比較兩個字符。如果第一個字符大於第二個字符,則將它們交換並循環,直到完成。在字詞的情況下,您必須迭代字符串,並且遍歷它們的字符以進行必要的交換。下面是一個示例:

#include <stdio.h> 

int s_bubblesort(int argc,char **argv); 

int main(void) 
{ 
    char *elements[9] = { "zab","aaaa","bac","zzz","abc","cab","aaa","acc","aaaaaaaaa" }; 

    s_bubblesort(9,elements); 

    for(int n = 0 ; n < 9 ; n++) 
    { 
     printf("%s\n",elements[n]); 
    } 
} 

int s_bubblesort(int argc,char **argv) 
{ 
    //loop variables 
    int i,j; 

    //p_1 : pointer that points to current string,p_2 : pointer that points to next string 
    char *p_1 , *p_2 , *tmp; 

    for(j = 0 ; j < argc ; j++) 
    { 
     for(i = 0 ; i < argc - j - 1 ; i++) 
     { 
      //assign p_1 to current string,and p_2 to next string 
      p_1 = argv[i] , p_2 = argv[i+1]; 

      //while *p_1 != '\0' and *p_2 != '\0' 
      while(*p_1 && *p_2) 
      { 
       //if *p_1 less than *p_2,break and move to next iteration 
       if(*p_1 < *p_2) 
        break; 

       else if(*p_1 > *p_2 || (! *(p_2 + 1) && (*p_1 == *p_2) && *(p_1+1))) // if *p_1 > *p_2,or *(p_2 + 1) == '\0' and *p_1 == *p_2 and *(p_1 + 1) != '\0' { SWAP } 
       { 
        tmp = argv[i]; 

        argv[i] = argv[i+1]; 

        argv[i+1] = tmp; 

        break; 
       } 
       p_1++; 
       p_2++; 
      } 
     } 
    } 
    return 0; 
}