Advertisement
zvezdomirov98

UP-homework-2

Dec 9th, 2019
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #include<iostream>
  2.  
  3. int substrOccurrences(char*, char*, int&);
  4. int myStrLen(char*);
  5.  
  6. int main()
  7. {
  8. char* str = new char[100];
  9. char* substr = new char[100];
  10. int maxIndex = -1;
  11.  
  12. std::cout << "Enter a string: ";
  13. std::cin.getline(str, 100);
  14. std::cout << "Enter a substring you are looking for: ";
  15. std::cin.getline(substr, 100);
  16.  
  17. int occurences = substrOccurrences(str, substr, maxIndex);
  18. std::cout << "Index: " << maxIndex << std::endl;
  19. std::cout << "Length: " << occurences << std::endl;
  20. }
  21.  
  22. int substrOccurrences(char* str, char* substr, int& maxIndex)
  23. {
  24. if (str == nullptr || substr == nullptr)
  25. {
  26. return -1;
  27. }
  28.  
  29. int strLength = myStrLen(str);
  30. int substrLength = myStrLen(substr);
  31.  
  32. int i = 0, j = 0;
  33. int occurrenceCount = 0, maxOccurrence = 0;
  34. int tempCount = 0;
  35.  
  36. while (i < strLength)
  37. {
  38. while (str[i++] == substr[j++])
  39. {
  40. tempCount++;
  41. if (tempCount == substrLength)
  42. {
  43. occurrenceCount++;
  44. tempCount = 0;
  45. j = 0;
  46. }
  47. }
  48. if (occurrenceCount > maxOccurrence)
  49. {
  50. maxOccurrence = occurrenceCount;
  51. maxIndex = i - (substrLength * maxOccurrence) - 1;
  52. }
  53. j = 0, tempCount = 0, occurrenceCount = 0;
  54. }
  55. return maxOccurrence * substrLength;
  56. }
  57.  
  58. int myStrLen(char* str)
  59. {
  60. if (str == nullptr)
  61. {
  62. return -1;
  63. }
  64.  
  65. int count = 0;
  66. while (*str++)
  67. {
  68. count++;
  69. }
  70. return count;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement