Say you are in chat room and in it there are 3 users.
paul127, mary532, mark456
You type pau and press tab to automatically complete paul's user name. The following code prototypes that feature.
Code:
/*
autocomplete.c
version 0.1
You know in irc chat room you want to type a user's name quickly, you type a portion of his user name and press tab? This code prototypes that functionality.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* search1="";
const char* search2="app";
const char* search3="apple tree";
char* strings1[3]={"","",""};
char* strings2[3]={"app","apple treehouse","apple treehouse"};
char* match(const char* search, char** strings, int n) {
if (n==0) {
return "";
}
if (n==1) {
if (!strcmp(search, "")) {
return strings[0];
}
else {
if (!strncmp(strings[0], search, strlen(search))) {
return strings[0];
}
else return "";
}
}
if (n>1) {
int i=1;
int j=n-1;
int k=1;
char result[20]="";
if (!strcmp(search, "")) {
while (j-- && strings[i]) {
if (!strncmp(strings[0], strings[i], k)) continue;
else return "";
++i;
}
strncpy(result, strings[0], 1);
result[1]='\0';
char* r=(char*)malloc(20*sizeof(char));
strcpy(r, result);
k++;
i=1;
j=n-1;
while (k<=strlen(strings[0])) {
while (j-- && strings[i]) {
if (!strncmp(strings[0], strings[i], k)) continue;
else return r;
++i;
}
i=1; j=n-1;
strncpy(result, strings[0], k);
result[k++]='\0';
strcpy(r, result);
}
return r;
}
if (strlen(search)>=1) {
int dd[n]; dd[0]=0;
i=0; j=n; k=strlen(search); int l=0;
while (strings[i] && j--) {
if (!strncmp(strings[i], search, k)) {
dd[l++]=i+1;
}
++i;
}
char* s=(char*)malloc(20*sizeof(char));
i=1; j=l-1; k=strlen(search)+1;
if (dd[0]>0) {
strcpy(s, search);
while (k<=strlen(strings[dd[0]-1])) {
while (j--) {
if (!strncmp(strings[dd[0]-1], strings[dd[i++]-1], k)) continue;
else return s;
}
j=l-1; i=1;
strncpy(result, strings[dd[0]-1], k);
result[k++]='\0';
strcpy(s, result);
}
return s;
}
else return "";
}
}
}
int main() {
puts(match(search1, strings2, 3)); // app
puts(match(search2, strings2, 3)); // app
puts(match(search3, strings2, 3)); // apple treehouse
return 0;
}