Fetch substring from the given string and display the sub-string starting and ending position. Also, print the substring and its length
Runtime Input :
programming
program
Output :
0 6
Length is 7
#include <stdio.h>
#include <conio.h>
void main(){
char inputString[100];
char inputSubstring[100];
int i,j;
int startingPosition=0;
int endingPosition=0;
int length=0;
printf("Enter string: ");
gets(inputString);
printf("Enter substring: ");
gets(inputSubstring);
for(j=0;inputSubstring[j]!='\0';j++){
length++;
}
for (i = 0, j = 0; inputString[i] != '\0' && inputSubstring[j] != '\0'; i++)
{
if (inputString[i] == inputSubstring[j])
{
j++;
}
else
{
j = 0;
}
}
if (j == length){
startingPosition=i - j;
endingPosition=startingPosition+length-1;
printf("%d %d\n",startingPosition,endingPosition);
printf("Length is %d\n\n",length);
}else{
printf("Substring not found\n\n");
}
getch();
}
Comments
Leave a comment