Funkce strReplace() v jazyce C

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;
}

79 Responses to Funkce strReplace() v jazyce C

  1. Pingback: PHILIP

  2. Pingback: ALFRED

  3. Pingback: BRUCE

  4. Pingback: GLENN

  5. Pingback: BRETT

  6. Pingback: LEROY

  7. Pingback: JASON

  8. Pingback: RONALD

  9. Pingback: VINCENT

  10. Pingback: VINCENT

  11. Pingback: BRYAN

  12. Pingback: LEWIS

  13. Pingback: BRUCE

  14. Pingback: RONNIE

  15. Pingback: MITCHELL

  16. Pingback: AARON

  17. Pingback: ALVIN

  18. Pingback: RUSSELL

  19. Pingback: RAUL

  20. Pingback: VINCENT

  21. Pingback: BRAD

  22. Pingback: EARL

  23. Pingback: DARRYL

  24. Pingback: MELVIN

  25. Pingback: JULIUS

  26. Pingback: ALFRED

  27. Pingback: RICK

  28. Pingback: CLINTON

  29. Pingback: greg

Napsat komentář

Vaše emailová adresa nebude zveřejněna. Vyžadované informace jsou označeny *

*

Můžete používat následující HTML značky a atributy: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam protection by WP Captcha-Free