Monday, 30 June 2014

Substrings

Write a program that takes two input strings S1 and S2 and finds if S2 is a substring of S1 or not. If S2 is a substring of S1, the program should print the index at S1 at which there is a match. If S2 is not a substring of S1, the program should print -1. If S2 appears in S1 multiple times, print the first index in S1 at which the match occurred.

INPUT:
Two strings S1 and S2, separated by whitespace.

OUTPUT:
One integer, which is either the index at which the match occurred or -1. Remember, the indices start at 0 for arrays.

CONSTRAINTS:
Each string contains at most 19 characters.
The strings will contain only letters from the alphabet (a-z and A-Z).
Match has to be case-sensitive.

Solution:

#include<stdio.h>
#include<string.h>
#define MAXLENGTH 20
#define INVALID_POSITION -1
int main(){
char str[MAXLENGTH];
char substr[MAXLENGTH];
scanf("%s%s",str,substr); // scan the string and the substring
int size_of_str = strlen(str);
int size_of_substr = strlen(substr);
int str_index=0;
int substr_index=0;
/* position of match. initialized to -1*/
int position_of_match = INVALID_POSITION;
/* Search till the end of string or till a match is found. */
while(str_index<size_of_str){
/* Match first character of sub string.
Once the first character is matched check if the required substring
starts there. */
if(substr[0] == str[str_index]){
for(substr_index=1;substr_index<size_of_substr;substr_index++){
if((str_index+substr_index)>= size_of_str)
break; // We have reached the end of string before end of substring. No match...
if(substr[substr_index] != str[str_index+substr_index])
break; // a miss match between two strings at this position. No match here.
}
if(substr_index == size_of_substr){ // Great!!! we have matched the string
position_of_match = str_index;
break; // we have got the match. Now stop searching.
}
}
str_index++;
}
printf("%d",position_of_match);
return 0;
}

No comments: