There is such a task:

"In the line, instead of spaces, insert a comma and a space."

How to solve it? I think using the lines. But he changed his mind. Put on the right path.

  • Here we still have to decide for ourselves: each space (including a single) is replaced by “,” or a group of spaces with “,” or something else. - avp

1 answer 1

Yes, as already written, in C there is no standard function for replacing substrings. But it is easy to write it yourself. Here, for example, my govnokod:

char* replace_substring(const char *source, const char *substring, const char *replace_with) { size_t substring_s = strlen(substring); size_t replace_with_s = strlen(replace_with); size_t source_s = strlen(source); char *result = malloc(source_s + 1); char *ptr = result; if(!ptr) return 0; while(*source) { /* Копируем исходную строку до тех пор, пока не встретим нужную подстроку */ if (strncmp(source, substring, substring_s)) { *ptr++ = *source++; } else { ptr -= (int)result; /* Меняем размер новой строки (так как $substring и $replace_with - не всегда будут одиноковы по длине) */ result = realloc(result, source_s += (replace_with_s - substring_s)); /* Копируем $replace_with в новую строку */ ptr += strlen(strcpy(ptr = result + (int)ptr, replace_with)); /* Следующий проход цикла начнем уже со следующего за найденной подстрокой символа */ source += substring_s; } } *ptr = 0; return result; } 
  • Thank you kind man, otherwise the training program is going too fast. Just simply do not have time to hand over the labs (((( Timi
  • one
    By doing realloc () in this task inside the loop, do you want to save memory? I'm afraid to disappoint, but really (without streams and signal handlers that simultaneously claim to be memory) will fail. It is necessary to calculate the maximum possible length of the result (based on the difference in length of the sample and replacement), to make malloc (), to form a result in a cycle, and at the end to make realloc (), returning the excess. one). Faster. 2) We will request no more memory from the system (or rather less). - avp
  • @avp thanks for the advice, I will consider. - VioLet