Guest User

Untitled

a guest
Jul 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. /*
  2. * 300154622
  3. * Exercise 02
  4. * Question 4
  5. * Avner Schwartz
  6. */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11.  
  12. typedef int BOOL;
  13.  
  14. #define FALSE 0
  15. #define TRUE 1
  16.  
  17. char* sqzstr(char* haystack, char* needles);
  18.  
  19. void main() {
  20. char* res;
  21. res = sqzstr("hello world", "l");
  22. res = sqzstr("", "or");
  23. printf("%s\n", res);
  24. free(res);
  25. }
  26.  
  27. char* sqzstr(char* haystack, char* needles) {
  28. static int counter = 0;
  29. static char* res;
  30. int i, j, writeInd, haystackLen;
  31. BOOL isNeedleInHaystack;
  32. writeInd = 0;
  33. i = 0;
  34.  
  35. // increment the local static counter each time sqzstr is called
  36. counter++;
  37. // use malloc only if it's the first time sqzstr was called
  38. if (counter == 1) {
  39. haystackLen = strlen(haystack);
  40. res = (char*)malloc(haystackLen * sizeof(char));
  41. if (res == NULL) {
  42. exit(1);
  43. }
  44. }
  45.  
  46. // if the stack argument is NULL or empty and the res pointer isn't NULL
  47. if ((haystack == NULL || strcmp(haystack, "") == 0) && (res != NULL)) {
  48. // call the sqzstr function again with the local static string res as haystack argument
  49. res = sqzstr(res, needles);
  50. }
  51. else {
  52. // as long as we didn't reach the end of haystack
  53. while (haystack[i] != '\0') {
  54. j = 0;
  55. isNeedleInHaystack = FALSE;
  56. // as long as we didn't reach the end of needles and the current needle isn't in the haystack
  57. while (needles[j] != '\0' && isNeedleInHaystack == FALSE) {
  58. if (needles[j] == haystack[i]) {
  59. isNeedleInHaystack = TRUE;
  60. }
  61. j++;
  62. }
  63. // if current needle is indeed not found in the haystack, copy it to the res string
  64. if (isNeedleInHaystack == FALSE) {
  65. res[writeInd] = haystack[i];
  66. writeInd++;
  67. }
  68. i++;
  69. }
  70. res[writeInd] = '\0';
  71. res = (char*)realloc(res, (writeInd+1) * sizeof(char));
  72. if (res == NULL) {
  73. exit(1);
  74. }
  75. }
  76. return res;
  77. }
  78. /*============== PROGRAM TEST RUNS ==============
  79. he wd
  80. Press any key to continue . . .
  81. */
Add Comment
Please, Sign In to add comment