Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- char* substring(char *string, int position, int lg)
- {
- char *p;
- int c;
- p = (char*) malloc((lg + 1) * sizeof(char));
- if(p == NULL)
- return "";
- for(c = 0; c < lg; ++c)
- p[c] = *((string + position) + c);
- p[c] = '\0';
- return p;
- }
- void insert_substring(char *a, char *b, int position)
- {
- char *f, *e;
- int lg;
- lg = strlen(a);
- f = substring(a, 0, position);
- e = substring(a, position, lg - position + 1);
- strcpy(a, "");
- strcat(a, f);
- free(f);
- strcat(a, b);
- strcat(a, e);
- free(e);
- }
- char* find_and_recolor(char* text, char* pattern)
- {
- int lgpattern = strlen(pattern);
- int lgreplace = lgpattern + 10;
- int dif = 0;
- char *p;
- while((p = strstr(text + dif, pattern)))
- {
- dif = p - text;
- //
- insert_substring(text, "\e[0;31m", dif);
- insert_substring(text, "\e[m", dif + lgpattern + 7);
- //
- p += lgreplace;
- dif = p - text;
- }
- return strdup(text);
- }
- char* read_line(char* pchar)
- {
- char temp[200];
- fgets(temp, 200, stdin);
- int lg = strlen(temp) - 1;
- temp[lg] = 0;
- pchar = (char*)malloc(lg * sizeof(char));
- strcpy(pchar, temp);
- char *dup = strdup(pchar);
- free(pchar);
- return dup;
- }
- int main()
- {
- int n;
- char pattern[30];
- fgets(pattern, 200, stdin); //citim pattern
- pattern[strlen(pattern) - 1] = 0; //scoatem \n din finalul array-ului
- scanf("%d\n", &n); //citim n
- char **text = malloc(n * sizeof(char*)); //alocare dinamica pentru urmatoarele n linii
- char *ex = malloc(n * sizeof(char)); //alocare dinamica pentru array exista.
- // ex poate sa fie char pentru ca ia doar valori 1/0
- int i;
- for(i = 0; i < n; ++i) //parcurgem n linii
- {
- text[i] = read_line(text[i]); //citim si alocam spatiu pentru fiecare linie
- if(strstr(text[i], pattern)) //daca am gasit macar o data pattern in linia curenta
- {
- find_and_recolor(text[i], pattern); //atunci gasim toate aparitiile lui pattern si inseram caracterele string-urile pentru culoare
- ex[i] = 1; //marcam ca linia i contine pattern
- }
- else
- ex[i] = 0; //marcam ca linia i nu contine pattern
- }
- for(i = 0; i < n; ++i)
- if(ex[i]) //daca exista pattern pe linia i
- printf("%s\n", text[i]); //atunci afisam
- free(ex); //eliberam memoria
- free(text);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement