Ad

Sunday, June 10, 2007

String Searching Function in C++

Nothing much to say, here I present you with a searching function. It takes two-character string (array) as the argument and finds the position of the second string in the first. For example, if the two arrays passed to the function have the following values:

String 1: ”I like C++” String 2: “C++”

then the function will return 7, because as an array, string 1 has the word C++ starting from the index number 7.

If the function cannot find the second string inside first then it will return the value -1, indicating that the search was unsuccessful.

The program below is easy to understand; therefore, I have left it up to you to understand how it is working.

   //C++ program which searches for a substring
   //in the main string
   #include<stdio.h>
   int search(char *string, char *substring);

   void main(void)
   {
   char s1[50], s2[30];
   int n;

   puts("Enter main string: ");
   gets(s1);
   puts("Enter substring: ");
   gets(s2);
   n=search(s1,s2);

   if(n!=-1)
     {
     puts("Index Number: ");
     printf("%d", n);
     }
   else
     puts("The substring cannot be found...");
   }


   //FUNTION DEFINITION
   //this function takes two arguments
   //first is the pointer to the main
   //string and second argument is the
   //pointer to the substring
   //it returns the index number of the
   //main string where the substring is found
   int search(char *string, char *substring)
   {
   int i=0,j=0, yes=0, index;

   while(string[i]!='\0')
     //search until the end of the string
     {
     if(string[i]==substring[j])
       {
       index=i;

       for (j=1;substring[j];j++)
         //match characters until
         //the end of substring
         {
         i++;

         if(string[i]==substring[j])
           yes=1;
         else
           {
           yes=0;
           break;
           }
         }
       if(yes==1) return index;
       }
     i++;
     j=0;
     }
   return -1;
   }

Hope this helps!

Related Articles:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.