aboutsummaryrefslogtreecommitdiff
path: root/plugins/strings
diff options
context:
space:
mode:
authorNunoSempere <nuno.semperelh@protonmail.com>2024-03-23 17:35:44 -0300
committerNunoSempere <nuno.semperelh@protonmail.com>2024-03-23 17:35:44 -0300
commit978c7ca1ccda4fc1138c607b2ffaa9fede60bf08 (patch)
tree637df171013cd4c7fce33a3b663a0a13293071e2 /plugins/strings
parentc8ff246cc256633820a18d6cc149d027082216e1 (diff)
change formatting + refactor string code
Diffstat (limited to 'plugins/strings')
-rw-r--r--plugins/strings/strings.c61
-rw-r--r--plugins/strings/strings.h2
2 files changed, 63 insertions, 0 deletions
diff --git a/plugins/strings/strings.c b/plugins/strings/strings.c
new file mode 100644
index 0000000..59bfdc9
--- /dev/null
+++ b/plugins/strings/strings.c
@@ -0,0 +1,61 @@
+#include <stdbool.h>
+#include <stdio.h>
+#include <string.h>
+
+#define DEBUG false
+
+// String manipulation
+void str_init(char* str, int n)
+{
+ // could also use <https://manpages.ubuntu.com/manpages/impish/man3/strinit.3pub.html>
+ for (int i = 0; i < n; i++)
+ str[i] = ' ';
+ str[n] = '\0';
+}
+int str_replace_start(const char* string, const char* target, const char* replacement, char* output)
+{
+ int l1 = strlen(string);
+ int l2 = strlen(target);
+ int l3 = strlen(replacement);
+ int l4 = strlen(output);
+
+ if (DEBUG) {
+ printf("string: %s, target: %s, replacement: %s, output: %s\n", string, target, replacement, output);
+ printf("%d,%d,%d,%d\n", l1, l2, l3, l4);
+ }
+
+ if ((l4 < (l1 - l2 + l3)) || l4 < l1) {
+ printf("Not enough memory in output string.\n");
+ return 1;
+ }
+ int match = true;
+ for (int i = 0; i < l2; i++) {
+ if (string[i] != target[i]) {
+ match = false;
+ break;
+ }
+ }
+ if (match) {
+ if (DEBUG) printf("Found match.\n");
+ for (int i = 0; i < l3; i++) {
+ output[i] = replacement[i];
+ }
+ int counter = l3;
+ for (int i = l2; i < l1; i++) {
+ output[counter] = string[i];
+ counter++;
+ }
+ output[counter] = '\0';
+ return 2; // success
+ } else {
+ if (DEBUG) printf("Did not find match.\n");
+ strcpy(output, string);
+ }
+
+ return 0;
+}
+/*
+See also:
+* <https://web.archive.org/web/20160201212501/coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring>
+* https://github.com/irl/la-cucina/blob/master/str_replace.c
+*/
diff --git a/plugins/strings/strings.h b/plugins/strings/strings.h
new file mode 100644
index 0000000..df08c75
--- /dev/null
+++ b/plugins/strings/strings.h
@@ -0,0 +1,2 @@
+void str_init(char* str, int n);
+int str_replace_start(const char* string, const char* target, const char* replacement, char* output);