Search a word in sentence or phrase without string function and pointers and indicate its position
This is a simple algorithm designed to search consecutive letters in a phrase or word in a given sentence and display the position of its first character in given phrase or string, The best part is that in this algorithm neither pointer function is used nor string function is used. It is based on very simple basic logic of arrays.
CODE
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int a[100]; // to store string or phrase
int b[20]; // to store word or letters to search
int c[20]; // to store the position of first character that match
int i=0,j=0;
printf("\n Enter sentence or phrase \n");
while((a[i++]=getche())!='\r');
i--;
printf("\n Enter word or letters to search for \n");
while((b[j++]=getche())!='\r');
j--;
int k=0; // no. of times 1st char. repeated
for (int s=0; s<i ; s++)
// This loop is to check the 1st character that match with phrase or sentence
// and store its position in c[] .
{
if(b[0]==a[s])
c[k++]=s;
}
int w,fc;
int v=0 ; // count all matches other than 1st char.
int m=0; // indicate that word match or not.
for(int x=0; x<k; x++)
// This loop is to check all cases of first char. match.
{
v = 0 ;
fc = c[x]; // store postition of 1st matched char.
w = fc + 1; // next char. to 1st mathced one.
for(int z=1; z<j; z++)
// This loop is to check the match of letters either consecutive or not.
// i.e match rest of char. of b[].
{
if(b[z]==a[w++])
v++;
}
// j is the total amount of letters to be matched
// j - 1 to exclude 1st char.
if(v==(j-1))
{ printf("\n \n Matched all letters at %d postion",fc+1);
m++; // word match or not.
}
}
if(m==0)
printf("\n Matched not found");
getch();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Enjoy !!!
Must visit an alternate code with different logic + logic's animation to get ..
C-search-word-in-sentence
Must visit an alternate code with different logic + logic's animation to get ..
C-search-word-in-sentence




nICe Logic ,used by admin
ReplyDeleteWithOut STRing aNd PointEr it is hard and U manaGe It niceLy ... >>