Консультация № 93640
02.07.2007, 12:47
0.00 руб.
0 3 3
Здравствуйте, уважаемые эксперты!
Помогите написать следующую функцию на C:
char* str_replace(char* source, char* fromtext, char* totext);
Она дожна заменять все вхождения подстроки fromtext на подстроки totext. Замена производится в строке source.
(получается аналог функции ansireplacestr в Delphi).
Функцию нужно сделать на C (не C++ (!)), чтобы её можно было скомпилировать под linux компилятором gcc.
Готовой такой функции в string.h я не нашел. Пытался написать подобное с помощью цикла с фукцией strtok, вылезают ошибки с памятью.
Подскажите, как по-проще это можно реализовать. Спасибо.

Обсуждение

Неизвестный
02.07.2007, 15:03
общий
это ответ
Здравствуйте, Alexius!
См. в приложении
прим. не стал переименовывать s1,s2,s3 но порядок указателей как в вопросе

Приложение:
char* s_replace(char *s1, char *s2, char *s3){int i,j,g,f,k,w,h;i=0; while(s1[i]!=NULL) {j=f=0; while(s2[j]!=NULL){ if (s1[i]==s2[j]) {f++; if (f==1) g=i; i++; j++; }else {f=0; break; } } if(f) {h=i; w=length(s1)-h; char *tmp1=new char[g+1]; char *tmp2=new char[w+2]; for(k=0; k<g; k++) *(tmp1+k) = *(s1+k); tmp1[k]=NULL; for(k=0; k<w+1; k++) *(tmp2+k) = *(s1+h+k); tmp2[k]=NULL; strcat(tmp1,s3); strcat(tmp1,tmp2); i=g+length(s3); s_copy(s1,tmp1); delete [] tmp1; delete [] tmp2; } while (s1[i]!=s2[0]) {++i; break;} } return s1;}
Неизвестный
03.07.2007, 04:41
общий
это ответ
Здравствуйте, Alexius!
Попробуйте вот этот вариант... Здесь заголовочный файл string.h вообще не используется. Код выполнен по стандарту С, так что любой компилятор должен с ним разобраться.

Приложение:
#include <malloc.h>#include <stdio.h>int str_len(const char *str) { int len = 0; while(str[len] != ‘\0‘) len++; return len;}int sub_str(const char *source, const char *sub) { int source_index = 0; int sub_index = 0; int sub_len = str_len(sub); while(source[source_index] != ‘\0‘) { if(source[source_index] == *sub) { while(source[source_index] != ‘\0‘ && sub[sub_index] != ‘\0‘) { if(source[source_index] == sub[sub_index]) { source_index++; sub_index++; continue; } else { sub_index = 0; break; } } if(sub_index == sub_len) return source_index - sub_len; } else source_index++; } return -1;}char* str_replace(const char* source, const char* from, const char* to) { int include_count = 0; int source_index = 0; int sub_index = 0; while((sub_index = sub_str(source + source_index, from)) != -1) { include_count++; source_index += sub_index + 1; } if(include_count == 0) return NULL; int from_len = str_len(from); int to_len = str_len(to); int replace_len = str_len(source) + (to_len - from_len) * include_count; char *replace_str = (char *)malloc(replace_len + 1); int replace_index = 0; source_index = 0; sub_index = 0; int to_index = 0; while(source[source_index] != ‘\0‘) { sub_index = sub_str((source + source_index), from); if(sub_index == -1) { while(source[source_index] != ‘\0‘) replace_str[replace_index++] = source[source_index++]; break; } while(sub_index-- > 0) replace_str[replace_index++] = source[source_index++]; while(to_index < to_len) replace_str[replace_index++] = to[to_index++]; source_index += from_len; to_index = 0; } replace_str[replace_len] = ‘\0‘; return replace_str;}int main(int argc, char* argv[]) { const char *source_str = "This is a test string"; printf("Initial string:\n%s\n", source_str); char *str = str_replace(source_str, "is", "tata"); printf("Modified string:\n%s\n", str); free(str); return 0;}
Неизвестный
03.07.2007, 10:38
общий
это ответ
Здравствуйте, Alexius!
вот...
char* str_replace(char *ssource,char *sfrom,char *stotext)
{
// обработка входной информации
if(ssource==NULL || sfrom==NULL || stotext==NULL)return NULL;
////////////////////////////////////////////////
char *s,*ptr=ssource,*out;
int lenfrom=strlen(sfrom),lento=strlen(stotext),numzamen=0,i=0,len=0;
while(s = strstr(ptr,sfrom))numzamen++,ptr=s+lenfrom;
if(numzamen==0)return ssource;
ptr=ssource;
len = strlen(ssource)- numzamen*(lenfrom-lento)+1;
out = new char[len+1];
memset(out,0x00,(len+1)*sizeof(char));
while(s=strstr(ptr,sfrom)){
i = s-ptr;
if(i){strncat(out,ptr,i);ptr += i;}// запоминаем символы между заменами
else{strncat(out,stotext,lento);ptr += lenfrom;}// вставляем замену
}
// добавляем конец строки
strcat(out,ptr);
return out;
}
Форма ответа