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

  • And this is exactly one task? Somehow the separators disappeared and the entered word appeared. As for strings: strings in C as a separate type do not exist, a string is an array of characters (char). A string is distinguished from a random array by the fact that it ends in a so-called. null character '\ 0' (in fact, it may not be there, but as long as it can be ignored), and it allows you not to drag everywhere along with the string its length. You can work with a string as with an array (because it is an array), also due to the equality '\ 0' == 0 you can do this hack: - etki
  • while (s [i]) {// will terminate as soon as it reaches '\ 0' char c = s [i]; i ++; } The main string functions can be connected using the header file string.h , there is, for example, the function strstr() , which allows you to find a substring in the string, and strlen() , which returns the length of the string by finding the null character position. - etki
  • Can I ask you in the program to show it? so it will be more clear - himiko
  • @himiko, what exactly? - etki
  • just a replacement for words - himiko

1 answer 1

 #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