-3

In C, how to redact or hide a substring such as "password" in a longer string such as "Hello password" replacing it with an arbitrary character such as '*' (repeated as necessary)?

Here is the intended usage for such a function, called redact:

#include <stdio.h>

int main()
{
    char s[] = "Hello password";
    printf("Input:\t\"%s\"\n", s);
    redact(s, "password", '*');
    printf("Output:\t\"%s\"\n", s);
}

Expected results:

Input: "Hello password"

Output: "Hello ********"

There are more general solutions involving replacement strings of arbitrary length and additional memory allocation that would not be as efficient for this special case:

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108

1 Answers1

-1

Here is an implementation of such a function redact:

// redact or hide a (repeated) substring, in place
// <https://stackoverflow.com/a/76592815/2103990>
bool redact (char *haystack, char *needle, char c) {
    char *p = strstr(haystack, needle);
    if (p == NULL)  return false;
    memset(p, c, strlen(needle));
    return redact(haystack, needle, c);
}

Bonus: it accounts for repetitions in the search substring:

Input: "Hello password password"

Output: "Hello ******** ********"

Demonstration:

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool redact (char *haystack, char *needle, char c);

int main()
{
    char s[] = "Hello password password";
    printf("Input:\t\"%s\"\n", s);
    redact(s, "password", '*');
    printf("Output:\t\"%s\"\n", s);
}

// (paste function redact here)
  • 1
    Why `strcpy` into `s` to initialize it when you could simply initialize it with `char s[100] = "Hello password";`? You also do not need to separately declare and initialize `t`, nor does returning it from `main` but not otherwise using it make much sense. – Chris Jul 01 '23 at 00:35
  • @Chris thanks for your suggestions, I've simplified the demo; the actual answer is function redact. – Felipe G. Nievinski Jul 01 '23 at 01:20