aboutsummaryrefslogtreecommitdiff
path: root/src/helper_functions.c
diff options
context:
space:
mode:
authoriceyrazor <iceyrazor@mailfence.com>2026-02-09 17:35:25 -0600
committericeyrazor <iceyrazor@mailfence.com>2026-02-09 17:35:25 -0600
commit5f08fd6e7794dcdfb74c93af16dfbc903458b0ea (patch)
treec10834b004e83afcde5228f9a9d0f9c91b29500e /src/helper_functions.c
parented16684cf50e2525072861cfd06e19ca4410b54f (diff)
split. better hostname
Diffstat (limited to 'src/helper_functions.c')
-rw-r--r--src/helper_functions.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/src/helper_functions.c b/src/helper_functions.c
new file mode 100644
index 0000000..9427b87
--- /dev/null
+++ b/src/helper_functions.c
@@ -0,0 +1,54 @@
+#ifndef shell_helper_functions
+#define shell_helper_functions
+
+#include <string.h>
+#include <unistd.h>
+
+// You must free the result if result is non-NULL.
+char *str_replace(char *orig, char *rep, char *with) {
+ char *result; // the return string
+ char *ins; // the next insert point
+ char *tmp; // varies
+ int len_rep; // length of rep (the string to remove)
+ int len_with; // length of with (the string to replace rep with)
+ int len_front; // distance between rep and end of last rep
+ int count; // number of replacements
+
+ // sanity checks and initialization
+ if (!orig || !rep)
+ return NULL;
+ len_rep = strlen(rep);
+ if (len_rep == 0)
+ return NULL; // empty rep causes infinite loop during count
+ if (!with)
+ with = "";
+ len_with = strlen(with);
+
+ // count the number of replacements needed
+ ins = orig;
+ for (count = 0; (tmp = strstr(ins, rep)); ++count) {
+ ins = tmp + len_rep;
+ }
+
+ tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
+
+ if (!result)
+ return NULL;
+
+ // first time through the loop, all the variable are set correctly
+ // from here on,
+ // tmp points to the end of the result string
+ // ins points to the next occurrence of rep in orig
+ // orig points to the remainder of orig after "end of rep"
+ while (count--) {
+ ins = strstr(orig, rep);
+ len_front = ins - orig;
+ tmp = strncpy(tmp, orig, len_front) + len_front;
+ tmp = strcpy(tmp, with) + len_with;
+ orig += len_front + len_rep; // move to next "end of rep"
+ }
+ strcpy(tmp, orig);
+ return result;
+}
+
+#endif