什么叫变位词? 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