Enter text from the keyboard, the number of lines of which is strictly 12, as well as an array of delimiters. In the lines in which the specified word occurs, replace this word with another one, also entered by the user. Delete the remaining lines. Print the received text on the screen and to a file.
Honestly, I do not understand what an array of delimiters is and it doesn't even get to me how to write it all. Therefore, I would like to ask for your help. C language only
|
1 answer
#include <stdio.h> #include <stdlib.h> #include <string.h> struct ds { char *data; int len; }; void append (struct ds *s, const char *src, int l1, const char *w, int l2) { int len = s->len + l1 + l2 + 1; if (!(s->data = (char *)realloc(s->data, len))) { perror("append str"); exit(-1); } memcpy(s->data + s->len, src, l1); memcpy(s->data + s->len + l1, w, l2); s->data[s->len += (l1 + l2)] = 0; } char * replstrw (const char *src, const char *w, const char *r, const char *sep) { struct ds s; s.data = 0; s.len = 0; const char *p, *tt = src, *t = src; int wl = strlen(w), rl = strlen(r); while (p = strstr(tt, w)) { if ((p == src || strchr(sep, p[-1])) && strchr(sep, p[wl])) { append(&s, t, p - t, r, rl); t = p + wl; } tt = p + wl; } if (s.data) append(&s, t, strlen(t), "", 0); return s.data; } int main (int ac, char *av[]) { char *res = replstrw("abc 12345 qabc abc 567", "abc", av[1] ? av[1] : "zxcv", " \n\t,."); if (res) puts(res); return 0; } If something is not clear, ask (tomorrow).
- struct, memcpy, blood, guts, replstrw ... And why did you invent strtok? - VadimTukaev
|
string.h, there is, for example, the functionstrstr(), which allows you to find a substring in the string, andstrlen(), which returns the length of the string by finding thenull characterposition. - etki