a. The following function returns the position of the FIRST occurrence of C-stri
ID: 3788024 • Letter: A
Question
a. The following function returns the position of the FIRST occurrence of C-string str2 in C-string str1. Complete the function using array access, i.e. str1[i], but no pointer access.
Note: For both part a) and part b) you may not use any library function calls (e.g. you cannot use strlen, strcat, etc. or other library functions)
// position of first occurrence of strt2 in str1
// return -1 if the string str2 does not occur
#include <stdio.h>
int first_occur_substr(char src[], char substr[])
{
//YOUR CODE HERE
}
int main()
{
char str1[100] = "";
char str2[7] = "PI3";
int pos = -1;
scanf("%s", str1); //get string from input keyboard
pos = first_occur_substr(str1,str2);
printf("first occurrence of %s in %s is %d ", str2, str1, pos);
}
b. Rewrite the above function, this time using pointer access, i.e. *str, but no array access.
Note: In general, a function’s parameter declarations “char str[]” and “char *str” are equivalent (i.e. they are interchangeable)
#include <stdio.h>
// position of first occurrence of strt2 in str1
// return -1 if the string str2 does not occur
int first_occur_substr_ptr(char *src, char *substr)
{
//your code here
}
int main()
{
char str1[100] = "";
char str2[7] = "PI3";
int pos1 = -1;
scanf("%s", str1); //get input string from keyboard
pos1 = first_occur_substr_ptr(str1, str2);
printf("first occurrence of %s in %s is %d %d ", str2, str1,pos1);
}
Explanation / Answer
Note : I have changed scanf("%s",str1) into scanf("%[^ ]s",str1) because the modified scanf will take even multi-word strings including white spaces
PART a:
#include <stdio.h>
int first_occur_substr(char src[], char substr[])
{
int i=0;
int j=0;
int temp=0;
int start=-1;
int flag=0;
while(src[i]!=''){
if(src[i]==substr[0]){
start=i;
flag=1;
temp=i;
j=0;
while(substr[j]!=''){
if(src[temp]!=substr[j]){
flag=0;
break;
}
temp++;
j++;
}
if(flag==1){
return start;
}
}
i++;
}
return -1;
}
int main()
{
char str1[100] = "";
char str2[7] = "PI3";
int pos = -1;
scanf("%[^ ]s", str1); //get string from input keyboard
pos = first_occur_substr(str1,str2);
printf("first occurrence of %s in %s is %d ", str2, str1, pos);
}
part b:
#include <stdio.h>
int first_occur_substr_ptr(char *src, char *substr)
{
int i=0;
int j=0;
int temp=0;
int start=-1;
int flag=0;
while(*(src+i)!=''){
if(*(src+i) == *(substr)){
start=i;
flag=1;
temp=i;
j=0;
while(*(substr+j)!=''){
if(*(src+temp) != *(substr+j)){
flag=0;
break;
}
temp++;
j++;
}
if(flag==1){
return start;
}
}
i++;
}
return -1;
}
int main()
{
char str1[100] = "";
char str2[7] = "PI3";
int pos = -1;
scanf("%[^ ]s", str1); //get string from input keyboard
pos = first_occur_substr_ptr(str1,str2);
printf("first occurrence of %s in %s is %d ", str2, str1, pos);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.