• 问题描述: 输入联想功能是非常实用的一个功能,请编程实现类似功能。 • 要求实现函数:
void auto_complete(char *str, char *tmp,char *output)
输入联想功能是非常实用的一个功能,请编程实现类似功能。要求实现函数:
void auto_complete(char *str, char *tmp,char *output)
【输入】 char *str,候选字符串
char *tmp,输入字符串
【输出】 int *output,联想匹配的字符串
【返回】 无
说明:候选字符串以空格隔开,输入字符串仅从字符串开始处匹配。将匹配的子字符串输出,同样以空格隔开。如无匹配成功的子字符串,则输出空字符串。
例如:
1) 输入:str = chengdu chongqing,tmp = c
输出:output = chengduChongqing
2) 输入:str = chengdu chongqing,tmp = che
输出:end = Chengdu
3)输入:str = beijing nanjing,tmp = jing
输出:end =
案例实现:
1 #include<stdio.h> 2 #include <string.h> 3 const int N=10005; 4 void auto_complete(char *str,char *tmp, char *output) 5 { 6 char word[N]; 7 memset(word,0,sizeof(word));//把word数组中的元素都重置为0 8 int i=0,k=0,j=0,cnt=0; 9 int len=strlen(str); 10 if(!strlen(tmp))//等效为strlen(tmp)==0 11 return; 12 while(*str)//循环当执行到结束讲结束循环 13 { 14 if(*str != ' ') 15 { 16 word[i++]=*str++;//把输入的第一个字符串赋给word数组 17 18 } 19 else 20 { 21 k=0;j=0; 22 23 while(k<i && tmp[j] != '\0') 24 { 25 if(word[k]==tmp[j])//比较两个字符串中字符相同的个数 26 { 27 k++; 28 j++; 29 } 30 else//如果出现不同的则结束循环 31 { 32 break; 33 } 34 } 35 if(tmp[j] == '\0')//把符合条件的字符串,赋给output并在其后加上一个空格 36 { 37 for(k=0;k<i;++k) 38 output[cnt++]=word[k]; 39 output[cnt++]=' '; 40 41 } 42 memset(word,0,i); 43 i=0; 44 *str++; 45 } 46 } 47 //以下的程序是为了解决最后的一个字符串 48 k=0;j=0; 49 while(k<i && tmp[j] != '\0') 50 { 51 if(word[k]==tmp[j]) 52 { 53 k++; 54 j++; 55 } 56 else 57 { 58 break; 59 } 60 } 61 if(tmp[j] == '\0') 62 { 63 for(k=0;k<i;++k) 64 output[cnt++]=word[k]; 65 66 } 67 output[cnt]='\0'; 68 } 69 int main() 70 { 71 void auto_complete(char *str,char *tmp, char *output); 72 char str[10000],tmp[100],output[10000]; 73 gets(str);gets(tmp); 74 auto_complete(str,tmp,output); 75 printf("%s\n",output); 76 return 0; 77 }
还有一个简单一点的:
1 #include <stdio.h> 2 #include <string.h> 3 void auto_complete(char*str,char*tmp,char *output) 4 { 5 int n,i=0,m; 6 char *p; 7 m=n=strlen(tmp); 8 p=tmp; 9 for(;*str;str++) 10 { 11 if(*str==' ') 12 continue; 13 if(*str==*tmp) 14 { 15 i++; 16 tmp++; 17 if(i==n) //目的字符串找到单词 18 { 19 if(*(str-n)>='a'&&*(str-n)<='z'||*(str-n)>='A'&&*(str-n)<='Z') 20 break; 21 while(1) //字符串复制 22 { 23 while(n-1) //复制N之前的字符 24 { 25 *output=*(str-n+1); 26 output++; 27 n--; 28 } 29 while(*str!=' ')//复制N及N之后与空格之间的字符 30 { 31 *output=*str; 32 output++; 33 str++; 34 } 35 *output=' '; 36 output++; 37 break; 38 } 39 tmp=p; //恢复到首地址 40 n=m; //恢复初值 41 i=0; //恢复初值 42 } 43 } 44 else 45 { 46 i=0; 47 tmp=p; //恢复到首地址 48 n=m; //恢复初值 49 } 50 } 51 *output=0; 52 } 53 void main() 54 { 55 char a[200],b[50],c[50]; 56 gets(a); //输入候选字符串 57 gets(b); //输入字符串 58 auto_complete(a,b,c); 59 puts(c); 60 }