Skip to content

Instantly share code, notes, and snippets.

@xeekworx
Created April 28, 2021 20:54
Show Gist options
  • Save xeekworx/d5fe177e2d80c739459ff8b12fcadfdc to your computer and use it in GitHub Desktop.
Save xeekworx/d5fe177e2d80c739459ff8b12fcadfdc to your computer and use it in GitHub Desktop.
FindString Example in C
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#define MATCH_NOT_FOUND SIZE_MAX
size_t findstring(const char* str, const char* match, size_t current_pos);
void main(void)
{
const char* redact_words[] = { "hello", "world" };
const int num_redact_words = 2;
char test_string[] = "Hello world in the world we call home and say hello!";
printf("Current test string: '%s'\n", test_string);
for (int i = 0; i < num_redact_words; i++) {
const char* match = redact_words[i];
size_t found_pos = MATCH_NOT_FOUND;
while ((found_pos = findstring(test_string, match, found_pos + 1, 0)) != MATCH_NOT_FOUND)
{
printf("Found at position: %I64d\n", found_pos);
memset(test_string + found_pos, '*', strlen(match));
}
}
printf("Changed test string: '%s'", test_string);
printf("\n");
}
size_t findstring(const char* str, const char* match, size_t pos, int ignore_case)
{
size_t match_pos = 0;
size_t match_len = strlen(match);
size_t start_match = MATCH_NOT_FOUND;
while (str[pos])
{
if ((!ignore_case && str[pos] == match[match_pos]) ||
(ignore_case && tolower(str[pos]) == tolower(match[match_pos])))
{
// In a potential match:
if (start_match == MATCH_NOT_FOUND) start_match = pos;
match_pos++;
}
else
{
// Reset
start_match = MATCH_NOT_FOUND;
match_pos = 0;
}
if (match_pos == match_len)
{
// Found full match, we're done
break;
}
pos++;
}
return start_match;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment