生活随笔
收集整理的這篇文章主要介紹了
找出词典中的所有的变位词 --By LXW
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
????????? 什么叫變位詞? least 和 tales是一對兒變位詞,create 和 cater也是一對兒變位詞!本程序是為了找出詞典中的所有變位詞!具體代碼如下:
這段代碼應該算是比較短的了,但這段確實不長的代碼足足花了我兩個晚上的時間!在編程的過程中遇到了一些平日里由于學習不扎實而引起的多個小問題,如char *類型的內存分配給遺漏了,以及函數strcpy使用時應該注意的問題還是沒有完全掌握... ...
//用此題加深輸入輸出重定向的理解和應用 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM 100
#define MAX 100//進行簽名
int charcomp (const void * a, const void * b){return ( *(char *)a - *(char *)b );
}void sign(){ char word[MAX], sig[MAX]; freopen("F:\\SOURCE.txt", "r", stdin); //待查找變位詞的文件【可以以一個字典中的所有單詞為例】freopen("F:\\STATION.txt", "w", stdout);while(scanf("%s", word) != EOF){ //若沒有分配空間就進行scanf,會有運行時錯誤strcpy(sig, word); qsort(sig, strlen(sig), sizeof(char), charcomp);printf("%s %s\n", sig, word);}fclose(stdin);fclose(stdout);
}//進行排序
void bubsort(char * * a, char * * b, int length){//此函數中***處代碼是為了,一旦判斷出數組中元素全部排好序后,就停止循環,提高效率int b1 = 0, b2 = length - 1; //b2為最大下標int i, t; //t為最后一次交換的位置char * temp;while(b1 < b2){for(i = b1; i < b2; ++ i){ //大的往后(上)移if(strcmp(a[i], a[i + 1]) > 0){temp = a[i]; //改變的是指針而不是字符串的內容!這樣效率高!a[i] = a[i + 1];a[i + 1] = temp;t = i;temp = b[i];b[i] = b[i + 1];b[i + 1] = temp;}}b2 = t;t = b1; //***for(i = b2; i > b1; -- i){ //小的往前(下)移if(strcmp(a[i], a[i - 1]) < 0){temp = a[i];a[i] = a[i - 1];a[i - 1] = temp;t = i;temp = b[i];b[i] = b[i - 1];b[i - 1] = temp;}}if(t == b1){ //*** //全部已經排好序b1 = b2; }else{b1 = t;}}
}int sort(char * * ownsig, char * * ownword){ //排序用交替冒泡排序int i = 0;freopen("F:\\STATION.txt", "r", stdin);while(scanf("%s %s", ownsig[i], ownword[i]) != EOF){++ i;}//根據本題,自己定義的排序:bubsort,交替冒泡排序。主要是對sig進行排序int length = i;bubsort(ownsig, ownword, length);fclose(stdin);return length;
}//進行擠壓
char * squash(char * word, char * sig, char * oldsig){if(strcmp(oldsig, sig) != 0 && strcmp(oldsig, "") != 0)printf("\n");strcpy(oldsig, sig);printf("%s\t", word);return oldsig;
}int main(){char * ownsig[NUM], * ownword[NUM];int j;for(j = 0; j < NUM; ++ j){ownsig[j] = (char *)malloc(MAX * sizeof(char));ownword[j] = (char *)malloc(MAX * sizeof(char));}char * oldsig = (char *)malloc(MAX * sizeof(char));int length;sign(); //void sign();length = sort(ownsig, ownword); //int sort(char * * ownsig, char * * ownword)strcpy(oldsig, ""); //若oldsig沒有分配空間(賦沒賦初值無所謂)則不能用strcpy賦值freopen("F:\\DESTINATION.txt", "w", stdout);//不斷地進行循環調用squash函數 j = 0;while(j < length){oldsig = squash(ownword[j], ownsig[j], oldsig);//char * squash(char * word, char * sig, char * oldsig);++ j;}printf("\n");fclose(stdout);for(j = 0; j < NUM; ++ j){free(ownsig[j]);free(ownword[j]);}free(oldsig);return 0;
}
?
如果您對本博文有什么意見,歡迎您與我聯系!【我的郵箱】:?lxw0109@gmail.com
總結
以上是生活随笔為你收集整理的找出词典中的所有的变位词 --By LXW的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。