Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 300154622
- * Exercise 02
- * Question 4
- * Avner Schwartz
- */
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- typedef int BOOL;
- #define FALSE 0
- #define TRUE 1
- char* sqzstr(char* haystack, char* needles);
- void main() {
- char* res;
- res = sqzstr("hello world", "l");
- res = sqzstr("", "or");
- printf("%s\n", res);
- free(res);
- }
- char* sqzstr(char* haystack, char* needles) {
- static int counter = 0;
- static char* res;
- int i, j, writeInd, haystackLen;
- BOOL isNeedleInHaystack;
- writeInd = 0;
- i = 0;
- // increment the local static counter each time sqzstr is called
- counter++;
- // use malloc only if it's the first time sqzstr was called
- if (counter == 1) {
- haystackLen = strlen(haystack);
- res = (char*)malloc(haystackLen * sizeof(char));
- if (res == NULL) {
- exit(1);
- }
- }
- // if the stack argument is NULL or empty and the res pointer isn't NULL
- if ((haystack == NULL || strcmp(haystack, "") == 0) && (res != NULL)) {
- // call the sqzstr function again with the local static string res as haystack argument
- res = sqzstr(res, needles);
- }
- else {
- // as long as we didn't reach the end of haystack
- while (haystack[i] != '\0') {
- j = 0;
- isNeedleInHaystack = FALSE;
- // as long as we didn't reach the end of needles and the current needle isn't in the haystack
- while (needles[j] != '\0' && isNeedleInHaystack == FALSE) {
- if (needles[j] == haystack[i]) {
- isNeedleInHaystack = TRUE;
- }
- j++;
- }
- // if current needle is indeed not found in the haystack, copy it to the res string
- if (isNeedleInHaystack == FALSE) {
- res[writeInd] = haystack[i];
- writeInd++;
- }
- i++;
- }
- res[writeInd] = '\0';
- res = (char*)realloc(res, (writeInd+1) * sizeof(char));
- if (res == NULL) {
- exit(1);
- }
- }
- return res;
- }
- /*============== PROGRAM TEST RUNS ==============
- he wd
- Press any key to continue . . .
- */
Add Comment
Please, Sign In to add comment