int search(char *source, char *pattern){
int result = 0;
while(*pattern != '\0'){
if(*pattern == '*'){
if(*(pattern+1) == '\0'){
pattern++;
}
else{
while((*source !='\0') && (*source != *(pattern+1))) source++;
if(*source == '\0'){
result = 1;
break;
}
else pattern++;
}
}
else if(*pattern == '?'){
moveNext(&source, &pattern);
}
else if ((*pattern >= 'A' && *pattern <= 'Z') ||
(*pattern >= 'a' && *pattern <= 'z')) {
if (*source == *pattern){
moveNext(&source, &pattern);
}
else{
result = 1;
break;
}
}
}
return result;
}
void moveNext(char **s,char **p){
(*s)++;
(*p)++;
}
int main()
{
char *source;
char *pattern;
source = (char *) malloc(sizeof(char)*200);
pattern = (char *) malloc(sizeof(char)*200);
printf("\tGrep Implementation (allowed operators are *, ?\n");
printf("\n\tEnter a Source String : ");
scanf("%s",source);
printf("\n\tEnter a pattern to Search : ");
scanf("%s",pattern);
if (search(source, pattern) == 0)
printf("\n\tString found\n");
else
printf("\n\tNot Found\n");
return 0;
}
Writing code and seeing our application automating a task is a great fun to see.
Tuesday, February 12, 2013
A Simple version of Grep with two meta-characters * and ?
Subscribe to:
Comments (Atom)