Given an array of strings I'm trying to find the index on which the given substring starts and ends. Here is my code:
#include <stdio.h>
void find_sub_string(char *str, char *sub){
int start= 0;
int end = 0;
int i=0,j=0;
while((str[i] != '\0') ){
if( str[i] == sub[j]){
if(j == 0){
start = i;
}
i++,j++;
} else if(str[i] != sub[j]){
j=0;
if(str[i] == sub[j]){
start = i;
j++,i++;
} else{
i++;
}
}
if (sub[j] == '\0'){
end = i-1;
printf("The start is: %d ,and end is : %d\n",start,end);
return;
}
}
printf("The substring %s was not found in string %s\n",sub,str);
return;
}
int main(){
char str[] = "internet";
char sub[] = "net";
find_sub_string(str,sub);
return 0;
}
I think the running time is O(n), but I'm not convinced because in the else if statement, I keep going back to the beginning of the substring (j=0) every time I see that str[i] != sub[j]. I'm concerned that it might cause the running time to be not O(n).
P.s This is NOT a homework question. I am just practicing problems.
jdoesn't matter in here because it doesn't affect how many iterations of the loop are ran. It'sO(n).printf("i=%d j=%d at line %d\n", i, j, __LINE__);to each "then" and "else" branch of the two inner if-else (so add else to the first one).