Advertisement
Guest User

Untitled

a guest
Mar 31st, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <stdbool.h>
  6.  
  7. #define LEN_MAX 128
  8.  
  9. bool find_string(char *sub, char *str, int len_of_str, int len_of_sub)
  10. {
  11. int arr_value[256];
  12.  
  13. for (int i = 0; i < 256; i++)
  14. arr_value[i] = len_of_sub;
  15.  
  16. for (int j = 0; j < len_of_sub - 1; j++) {
  17. char c = sub[j];
  18.  
  19. arr_value[c] = len_of_sub - j - 1;
  20. }
  21.  
  22. arr_value[sub[len_of_sub-1]] = len_of_sub;
  23.  
  24. for (int i = 0; i < len_of_sub; i++) {
  25. char c = sub[i];
  26.  
  27. printf("%d\n", arr_value[c]);
  28. }
  29.  
  30. bool found = false;
  31.  
  32. if (len_of_sub > len_of_str)
  33. return false;
  34.  
  35. for (int ind_of_str = 0; ind_of_str < len_of_str - len_of_sub + 1;) {
  36. int j;
  37.  
  38. for (j = len_of_sub - 1; j >= 0; j--) {
  39. if (sub[j] != str[ind_of_str + j])
  40. break;
  41. }
  42.  
  43. if (j < 0) {
  44. found = true;
  45. break;
  46. }
  47.  
  48. ind_of_str += arr_value[str[ind_of_str+j]];
  49.  
  50. }
  51. return found;
  52. }
  53.  
  54. int characters_input(char **str)
  55. {
  56. int curr_size = LEN_MAX;
  57. int lenght;
  58.  
  59. if (*str != NULL) {
  60. int i = 0;
  61. char c = EOF;
  62.  
  63. while ((c = getchar()) != '\n' && c != EOF) {
  64. *str[i++] = c;
  65. if (curr_size == i) {
  66. curr_size = i + LEN_MAX;
  67. *str = realloc(*str, curr_size);
  68. }
  69. lenght = i;
  70. }
  71. *str[i] = '\0';
  72. *str = realloc(*str, lenght + 1);
  73. }
  74.  
  75. return lenght;
  76. }
  77.  
  78. int main(void)
  79. {
  80. int len_of_str;
  81. int len_of_sub;
  82. char *str = malloc(LEN_MAX * sizeof(char));
  83. char *sub_str = malloc(LEN_MAX * sizeof(char));
  84.  
  85. printf("Enter your string:\n");
  86. len_of_str = characters_input(&str);
  87.  
  88. printf("Enter your substring:\n");
  89. len_of_sub = characters_input(&sub_str);
  90.  
  91. if (find_string(sub_str, str, len_of_str, len_of_sub))
  92. printf("Substring is found!");
  93. else
  94. printf("Substring isn't found!");
  95.  
  96. free(str);
  97. free(sub_str);
  98. return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement