char str1[50] = \"don\'t judge a book by its cover\"; char str2[40] = \"book\";
ID: 3624769 • Letter: C
Question
char str1[50] = "don't judge a book by its cover";
char str2[40] = "book";
Write a for loop with index i comparing 4 characters starting with str1+i to str2. Display the position in
str1 (that is index i) where a match is found.
//my code
#include <iostream>
using namespace std;
int findstr(char str[],char substr[]){
int i,r;
for(i=0;i<strlen(str);i++){
r=strncmp(str+1, substr, strlen(substr));
if(r==0)
return (i);
}
return (-1);
}
int main(){
char str[50] = "don't judge a book by its cover";
char substr[20] = "book";
int pos;
pos=findstr(str, substr);
}
Explanation / Answer
please rate - thanks
change the 1 to i, I added some output
#include <iostream>
using namespace std;
int findstr(char str[],char substr[]){
int i,r;
for(i=0;i<strlen(str);i++){
r=strncmp(str+i, substr, strlen(substr));
if(r==0)
return (i);
}
return (-1);
}
int main(){
char str[50] = "don't judge a book by its cover";
char substr[20] = "book";
int pos;
pos=findstr(str, substr);
if(pos>0)
cout<<substr<<" found at index "<<pos<<" of "<<str <<endl;
else
cout<<substr<<" not found in "<<str<<endl;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.