Другие языки программирования и технологии

Как заменить 2 пробела на 1? Си

Муторно это в C,
заменять в строке одну подстроку на другую:

// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep
int len_with; // length of with
int len_front; // distance between rep and end of last rep
int count; // number of replacements

if (!orig)
return NULL;
if (!rep || !(len_rep = strlen(rep)))
return NULL;
if (!(ins = strstr(orig, rep)))
return NULL;
if (!with)
with = "";
len_with = strlen(with);

for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}

// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);

if (!result)
return NULL;

while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}

То ли дело в C#:

s1 = s.Replace(oldStr, newStr) ...
Валерий Луганский
Валерий Луганский
87 201
Лучший ответ
Си сложная штука, не пойму, почему вы его выбрали? Я уже лет 6 си не использую, попытаюсь конечно сделать алгоритм.. . но не обещаю...
Сергей Летвин
Сергей Летвин
8 830
Код в студию.
Виталий Капустин #include <string.h>
#include <stdio.h>
#include <conio.h>
main()
{

char q[80];
int i;
printf("Введите строку\n");
gets (q);
i = 0;
while ( q !='\0')
{
if ( q == ' ' ) i ++;

printf ( "Результат: %s ", q );
_getch();
}

Похожие вопросы