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

C programming questions requirements: You CANNOT call any library functions // 7

ID: 3666960 • Letter: C

Question

C programming questions
requirements: You CANNOT call any library functions

// 7. Write a function that searches for the first occurrence of substring1 in string.

//    If substring1 is found, replace it with substring2.

//    Note that substring1 and substring2 do not necessarily have the same size.

//    The function returns the resulting string size if substring1 is found and replaced by substring2.

//    The string size does not include the terminating null character itself.

//    If substring1 is not found in string, the function returns -1.

//    Note that the caller must ensure that there is sufficient storage allocated to string to hold the new string.

int search_replace(char* string, char* substring1, char* substring2) {

    // TODO: add your code here

}

Explanation / Answer

void strreplace(char string[], char search[], char replace[]){ char buffer[100]; char*p = string; while((p=strstr(p, search))){ strncpy(buffer, replace); buffer[p-string] = ''; //EDIT: THIS WAS MISSING strcat(buffer, replace); strcat(buffer, p+strlen(search)); strcpy(string, buffer); p++; } }