Website Summary Files Commits Branches @commit @diff @stats
path: root / Sem. 12 / task3.cpp
diff options
context:
space:
mode:
Commit5c727824c4597c38fb4248ad20d3c9789201f0d3 (patch)
Author
 Angeld55 <angel_dimitriev@abv.bg>
2020-12-27 16:25:51 +0200
Committer
 Angeld55 <angel_dimitriev@abv.bg>
2020-12-27 16:25:51 +0200
Files5c995c476b5bcf3e4ce8401464472c551fea265e /Sem. 12/task3.cpp
Introduction_to_programming_FMI-5c727824c4597c38fb4248ad20d3c9789201f0d3.tar
Introduction_to_programming_FMI-5c727824c4597c38fb4248ad20d3c9789201f0d3.tar.gz
Introduction_to_programming_FMI-5c727824c4597c38fb4248ad20d3c9789201f0d3.zip
Parent5bd416a7bcc4bd6f6bac606b825c3f22e0b4530e (diff)
added sem 12
1 files changed, 89 insertions, 0 deletions
-rw-r--r--Sem. 12/task3.cpp89
diff --git a/Sem. 12/task3.cpp b/Sem. 12/task3.cpp
new file mode 100644
index 0000000..ba0ba1b
--- /dev/null
+++ b/Sem. 12/task3.cpp
@@ -0,0 +1,89 @@
+#include <iostream>
+using namespace std;
+
+int search(const char* string, const char* searched);
+
+void replace(const char* string, const char* x, const char* y, char* result)
+{
+ int yLen = strlen(y);
+ int xLen = strlen(x);
+ while (true)
+ {
+ int indX = search(string, x); //14
+ if (indX == -1)
+ break;
+
+
+ for (int i = 0; i < indX; i++)
+ result[i] = string[i];
+ result += indX;
+ string += indX + xLen;
+
+ for (int i = 0; i < yLen; i++)
+ result[i] = y[i];
+ result += yLen;
+ }
+
+ //the rest symbols
+ while (*string != '\0')
+ {
+ *result = *string;
+ result++;
+ string++;
+ }
+ *result = '\0';
+
+}
+
+//return the first index of searched in str.
+int search(const char* str, const char* searched)
+{
+ int len1 = strlen(str);
+ int len2 = strlen(searched);
+ for (int i = 0; i < len1 - len2+1; i++)
+ {
+ bool found = true;
+ for (int j = 0; j < len2; j++)
+ {
+ if (searched[j] != str[i + j])
+ {
+ found = false;
+ break;
+ }
+ }
+ if (found)
+ return i;
+ }
+ return -1;
+}
+int countOccurrences(const char* str, const char* searched)
+{
+ int count = 0;
+
+ int searchLen = strlen(searched);
+ int ind = search(str, searched);
+ while (ind != -1)
+ {
+ count++;
+ str += (ind + searchLen);
+ ind = search(str, searched);
+ }
+ return count;
+}
+int main()
+{
+ const char* str = "hello friends! You are my best friends. I have no other friends";
+ const char* x = "friend";
+ const char* y = "enemy";
+
+ int len = strlen(str);
+ int xOccurrences = countOccurrences(str, x);
+
+ char* result = new char[len - xOccurrences*strlen(x) + xOccurrences*strlen(y) + 1];
+
+ replace(str, x, y, result);
+
+ cout << result << endl;
+
+ delete[] result;
+} \ No newline at end of file