Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function that returns the index of character c in string str int index O

ID: 3826343 • Letter: W

Question

Write a function that returns the index of character c in string str int index Of(char * str, char c) Write a function that returns the index of substring sub in string str int indexOf(char * str, char sub) Write a function that returns the index of the last occurrence of character c in string str int lastIndexOf(char *str, char c) Write a function that returns the character at position idx in string str char charAt(char *str, int idx) Write a function that returns 1 if string str starts with the string sub, 0 otherwise int startsWith(char *str, char sub) Write a function that returns a new string consisting of the sequence of characters between the ith and jth index in str char substring(char *str, int i. int j)

Explanation / Answer

1. indexOf function which returns index of character c in string str.

int indexOf(char *str,char c){
int i,len;
len=strlen(str);
for(i=0;i<len;i++){
if(str[i]==c)
return i;
}

2. indexOf function that returns the index of substring sub in string str

int indexOf(char *str,char *sub){
int i,len,j,k,flag=0,sublen;
  
len=strlen(str);
sublen=strlen(sub);
for(i=0;i<len;i++){
if(str[i]==sub[0]){
for(j=1;j<sublen;j++){
if(str[j+i]==sub[j]){
flag=1;
}
else{
flag=0;
break;
}
}
if(flag==1){
return i;
}
}
}
}

3. function that returns the index of the last occurrence of character c in string str

int lastIndexOf(char *str,char c){
   int i,len;
   len=strlen(str);
   for(i=len-1;i<=0;i++){
       if(str[i]==c)
           return i;
   }
}

4. function that returns the character at position idx in string str

char charAt(char *str,int idx){
   return str[idx];
}

5. function that returns 1 if string str starts with the string sub,0 otherwise
int startsWith(char *str,char *sub){
   int i,sublen,flag=0;
   sublen=strlen(sub);
   for(i=0;i<sublen;i++){
       if(str[i]==sub[i])
           flag=1;
       else
           flag=0;
   }
   return flag;
}

6. function that returns a new string consisting of the sequence of characters between the ith and jth index in str

char *substring(char *str,int i,int j){
char *temp;
int k,length=j-i;
temp = malloc(length+1);
for (k = 0 ; k < length ; k++)
{
*(temp+k) = *(str+i-1);
str++;   
}

*(temp+k) = '';

return temp;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote