rosenrot-browser

A hackable browser based on Webkitgtk
Log | Files | Refs | README

strings.c (1671B)


      1 #include <stdbool.h>
      2 #include <stdio.h>
      3 #include <string.h>
      4 
      5 #define DEBUG false
      6 
      7 // String manipulation
      8 void str_init(char* str, int n)
      9 {
     10     // could also use <https://manpages.ubuntu.com/manpages/impish/man3/strinit.3pub.html>
     11     for (int i = 0; i < n; i++)
     12         str[i] = ' ';
     13     str[n] = '\0';
     14 }
     15 int str_replace_start(const char* string, const char* target, const char* replacement, char* output)
     16 {
     17     int l1 = strlen(string);
     18     int l2 = strlen(target);
     19     int l3 = strlen(replacement);
     20     int l4 = strlen(output);
     21 
     22     if (DEBUG) {
     23         printf("string: %s, target: %s, replacement: %s, output: %s\n", string, target, replacement, output);
     24         printf("%d,%d,%d,%d\n", l1, l2, l3, l4);
     25     }
     26 
     27     if ((l4 < (l1 - l2 + l3)) || l4 < l1) {
     28         printf("Not enough memory in output string.\n");
     29         return 1;
     30     }
     31     int match = true;
     32     for (int i = 0; i < l2; i++) {
     33         if (string[i] != target[i]) {
     34             match = false;
     35             break;
     36         }
     37     }
     38     if (match) {
     39         if (DEBUG) printf("Found match.\n");
     40         for (int i = 0; i < l3; i++) {
     41             output[i] = replacement[i];
     42         }
     43         int counter = l3;
     44         for (int i = l2; i < l1; i++) {
     45             output[counter] = string[i];
     46             counter++;
     47         }
     48         output[counter] = '\0';
     49         return 2; // success
     50     } else {
     51         if (DEBUG) printf("Did not find match.\n");
     52         strcpy(output, string);
     53     }
     54 
     55     return 0;
     56 }
     57 /*
     58 See also:
     59 * <https://web.archive.org/web/20160201212501/coding.debuntu.org/c-implementing-str_replace-replace-all-occurrences-substring>
     60 * https://github.com/irl/la-cucina/blob/master/str_replace.c
     61 */