Funkce strReplace() je funkce, která nahrazuje řetězec v řetězci.
Princip funkčnosti spočívá ve spočítání velikosti nového (výsledného) řetězce, alokace potřebné paměti a samotné nahrazovaní.
Pro své účely si ještě napíšeme jednoduchou funkci strpos(), která vrací pozici podřetězce v řetězci.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strpos(const char *find, const char *string, int start = 0)
{
int slen = strlen(string),
flen = strlen(find);
if (start >= slen)
return -1;
for(int i = start, j = 0; i < slen; i++)
{
for(j = 0; j < flen; j++)
if (string[i+j] != find[j])
break;
if (j == flen)
return i;
}
return -1;
}
char *strReplace(const char *find, const char *replace, const char *str)
{
int f_len = strlen(find),
r_len = strlen(replace),
s_len = strlen(str);
int fcount = 0, fpos = 0;
// zjistime kolikrat je hledany retezec find v retezci str
while((fpos = strpos(find, str, fpos+1)) != -1)
fcount++;
if (fcount == 0)
return (char *)str;
// spocitame pocet potrebnych znaku pro vysledny retezec
int str_size = (s_len - (fcount*f_len)) + (fcount*r_len);
// alokuje pamet pro novy retezec
char *str2 = (char *)malloc(sizeof(char)*str_size+1);
int lastpos = 0, j = 0;
for(int i = 0; i < s_len; i++)
{
if (lastpos <= i && lastpos != -1)
lastpos = strpos(find, str, i);
if (i == lastpos)
{
for(int k = 0; k < r_len; k++)
str2[j++] = replace[k];
i += f_len-1;
}
else
str2[j++] = str[i];
}
str2[j] = '\0';
return str2;
}
int main()
{
char str[] = "Hello my big world";
char *str2 = strReplace("big", "small", str);
printf("%sn", str2); // vypise: "Hello my small world"
free(str2);
return 0;
}
Pingback: LUKE
Pingback: EDUARDO
Pingback: BRANDON
Pingback: PERRY
Pingback: SALVADOR
Pingback: ROY
Pingback: ALFRED
Pingback: JEFFREY
Pingback: KIRK
Pingback: RUSSELL
Pingback: TERRENCE
Pingback: EDUARDO
Pingback: DONNIE
Pingback: ROLAND
Pingback: LEWIS
Pingback: RONALD
Pingback: DUSTIN
Pingback: ALFRED
Pingback: LESLIE
Pingback: CLAUDE
Pingback: BRETT
Pingback: WILLIE
Pingback: CHARLIE
Pingback: DONALD
Pingback: FELIX
Pingback: WALLACE
Pingback: VICTOR
Pingback: BRADLEY
Pingback: TONY
Pingback: BRUCE
Pingback: KENNY
Pingback: WILLIAM
Pingback: BOB
Pingback: BILLY
Pingback: JIMMY
Pingback: BYRON
Pingback: CARL
Pingback: RUBEN
Pingback: ADAM
Pingback: SERGIO
Pingback: CLIFTON
Pingback: VICTOR
Pingback: DARYL
Pingback: LAWRENCE
Pingback: LUIS
Pingback: JEREMIAH
Pingback: RODNEY
Pingback: LLOYD
Pingback: RAY
Pingback: MARCUS