Thursday, April 19, 2012

Efficient way to search a string in an array of string in C. (Case insensitive)

I am working on a project (implemented in C) where we are required to maintain a list of a features or keywords. The user enters a string. We need to do case insensitive search for this string in the stored array of string. The list currently consists of 100 strings and new strings may be added (5 strings a year or so).



I want to know the best way to store this array and make the search more efficient.



The solution which is currently implemented is something like below:(I have not compiled this code. This is just a code snippet.)



    char **applist={ asdf , adgh, eftg , egty, ...} 
char *user_input; // this string contains user entered string
int id;
switch(user_input[0])
{
case 'a':
case 'A':
switch(user_input[1]
{
case 's':
case 'S':
id=0
break;

case 'd':
case 'D':
id=1
break;
}
break;
case'e':
case'E':
switch(user_input[1])
{
case 'f':
case 'F':
id=2
break;

case 'g':
case 'G':
id=3
break;
}
break;
}
if(stricmp(user_input,applist[id]))
return id;
else
return -1;


In actual code applist is not sorted. As new strings are added to applist I need an efficient way to store this array.



If I store the string sorted alphabetically then every time a new string is added I have to manually find the correct position of the new string. (New Strings are added to applist before compiling the code not at the runtime)



Suggest an efficient way of doing this.



EDIT: My current approach leads to a longer code but its efficient. But this code is not easy to maintain. What I need is a data structure which can do search with same efficiency as this but with smaller code. The datastructure you suggest, should not have additional overhead. The only requirement is efficient searching. And a way to add elements to the data structure at compile time easily. Sorting at run-time is not my requirement as new strings are added at compile time(This is to avoid restrict user from adding any new string to the list).





No comments:

Post a Comment