#include /* You may NOT call any other string functions. * Do NOT include string
ID: 3529018 • Letter: #
Question
#include /* You may NOT call any other string functions. * Do NOT include string.h. * Do NOT alter main in any way. */ int hasSubstring(char w[], char sub[]); int main () { char word[10], substring[10]; printf("Word: "); scanf("%s", word); printf("Substring to search for: "); scanf("%s", substring); if (hasSubstring(word, substring)) { printf("%s contains the substring %s. ", word, substring); } else { printf("%s does NOT contain the substring %s. ", word, substring); } return 0; } int hasSubstring(char w[], char sub[]) { /* Write code here */ }Explanation / Answer
#include <stdio.h>
int hasSubstring( char w[], char sub[] );
int main() {
char word[10], substring[10];
printf( "word: " );
scanf( "%s", word );
printf( "Substring to search for:" );
scanf( "%s", substring );
if ( hasSubstring( word, substring ) ) {
printf( "%s contains the substring %s. ", word, substring );
} else {
printf( "%s does NOT the substring %s. ", word, substring );
}
}
int hasSubstring( char w[], char sub[] ) {
int found=0;
int i=0, j=0;
/* Repeat until we hit the end of w[] */
while( w[i] != '' ) {
/* Search for the first character of sub[] */
while( w[i] != '' && w[i] != sub[j] ) i++;
/* match w[] and sub[]. Stop when either we hit the end of
w[] or the end of sub[] */
while( w[i] != '' && sub[j] != ''
&& w[i] == sub[j] ) {
i++, j++;
}
/* If we've hit the end of sub[], we're done */
if ( sub[j] == '' ) return 1;
}
/* We hit the end of word[] -- not found */
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.