view playground/main.c @ 131:b230a743a01e

Added blog.
author June Park <parkjune1995@gmail.com>
date Fri, 09 Jan 2026 07:42:04 -0800
parents e7899c93da77
children 893d87124d16
line wrap: on
line source

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

int main() {
    char *input[5] = {"Hello ", "Foo <<E", "N", "DD>", "Park <END> "};
    char *key = "<END>";
    int key_len = strlen(key);

    char **buffers = malloc(sizeof(char *) * 100);
    int buffer_index = 0;
    int key_ptr = 0;
    for (int i = 0; i < 5; i++) {
        char *packet = input[i];
        int p_len = strlen(packet);

        for (int j = 0; j < p_len; j++) {
            if (packet[j] == key[key_ptr]) {
                key_ptr++;
                
                // If the WHOLE keyword is found
                if (key_ptr == key_len) {
                    // 1. Print all previous "safe" buffers
                    // (The ones before the one where the keyword started)
                    for (int b = 0; b < buffer_index; b++)
                        printf("%s", buffers[b]);
                    
                    // 2. Handle the "Current" packet truncation
                    // Calculate where the match started in THIS packet
                    // If key_ptr was satisfied across multiple packets, 
                    // 'j' is the end of the match in the current packet.
                    int match_end_in_packet = j + 1;
                    int match_len_in_this_packet = (key_ptr <= match_end_in_packet) ? key_ptr : match_end_in_packet;
                    
                    printf("%.*s\n", (match_end_in_packet - match_len_in_this_packet), packet);
                    
                    free(buffers);
                    return 0;
                }
            } else {
                // If a match fails, we must "flush" the buffers we were holding
                if (key_ptr > 0) {
                    for (int b = 0; b < buffer_index; b++) printf("%s", buffers[b]);
                    buffer_index = 0;
                    
                    if (packet[j] == key[0]) key_ptr = 1;
                    else {
                        printf("%c", packet[j]);
                        key_ptr = 0;
                    }
                } else {
                    printf("%c", packet[j]);
                }
            }
        }

        // If we finish a packet and we are in the middle of a match, buffer it
        if (key_ptr > 0) {
            buffers[buffer_index++] = packet;
        }
    }

    free(buffers);
    return 0;
}