Busqueda y reemplazo de cadenas en C

/*
 * Copyright (C) 2009 Moisés Brenes, http://mbrenes.blogspot.com
 *  
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software 
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * Any non-GPL usage of this software or parts of this software is strictly
 * forbidden.
 */
 
/* @ shakka
 *
 * blog > mbrenes.blogspot.com
 * web > radamanthys.homelinux.org
 * mail > moises.brenes@gmail.com
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
void strReplace(const char *search, const char *replace, const char *from, char *to)
{
char *pstr;
char *buffer;
int top;
int i;
int j;
int k;
 
	if (search == NULL || replace == NULL || from == NULL || (strlen(search) < 0) || (strlen(replace) < 0) || (strlen(from) < 0))
	{
		strcpy(to, "");
	}
	else
	{
		buffer = (char *) malloc(strlen(from) * sizeof(char *));
 
		k = 0;
		strcpy(to, from);
		pstr = strstr(to, search);
		while (pstr != NULL )
		{
			k = (k + 1);
 
			j = (strlen(to) - strlen(pstr));
			strncpy(buffer, to, j);
			buffer[j] = '\0';
 
			if (strlen(replace) > strlen(search))
				buffer = (char *) realloc(buffer, (strlen(from) + ((strlen(replace) - strlen(search)) * k)) * sizeof(char *));
 
			j = (j + strlen(replace));
			strncat(buffer, replace, strlen(replace));
			buffer[j] = '\0';
 
			i = strlen(search);
			top = strlen(pstr);
			while (i < = top)
			{
				buffer[j] = pstr[i];
 
				i = (i + 1);
				j = (j + 1);
			}
 
			buffer[j] = '\0';
 
			strcpy(to, buffer);
			pstr = strstr(to, search);
		}
	}
 
	free(buffer);
}

Esta funcion busca la cadena pasada como parametro(const char *search) y reemplaza(const char *replace) todas las ocurrencias encontradas. Cada quien es responsable en reservar suficiente espacio a la cadena resultante(char *to) para el volcado de la cadena original(const char *from) modificada con sus respectivos reemplazados, si estos fueran encontrados, de lo contrario la cadena to se devolvera vacia(no NULL).

Este articulo fue publicado por: shakka

 -----BEGIN GEEK CODE BLOCK-----
Version: 3.12
GCS d? s: a-- C++ UL++++ P+ L++ 
E- W++ N++ o-- K- w-- 
O- M- V- PS PE-- Y-- PGP++ t+++ 
5++ X++ R !tv b++ DI+++ D+ 
G++ e++ h+ !r y** 
------END GEEK CODE BLOCK------
Ver artículos del autor (73)


About this entry