Thursday 25 October 2012

Function041

Write a function to accept two strings as arguments. The function should return the index of the second string in the first string, if it exists and -1 otherwise. Don't use any library routines related to strings.

#include <stdio.h>
#include <conio.h>
void main ( )
{        
        char        str[80], substr[80];
        int           f;
        clrscr ( );
       
        printf("\n\n\n\t Enter the 1st string..:"); gets(str);
        printf("\n\t Enter the substring to search..:");
        gets ( substr );
        f = search ( str, substr );
        if ( f == -1 )
        {                                  
                 printf("\n\n\n\t String not found.");
        }                    
        else                         
        {                    
                 printf("\n\n\n\t String found in position %d",f);
        }
        getch ( );
}                         
                                   
int search ( char    str1[], char    str2[] )
{
        int     i = 0, f;
        for ( i = 0; str1[i] != '\0'; i++ )
        {                                     
                  if ( found ( str1, str2, i ) )
                                return i;
        }
        return -1;
}                     
                                          
int found ( char    str1[], char      str2[], int    i )
{                        
        int      j;
        for ( j = 0; str2[j] != '\0'; i++, j++ )
        {                                                
                  if ( str1[i] != str2 [ j] )
                             return 0;
        }
        return 1;
}
Click here to contact us

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...