Clunky C cleanup code

From: fatted (fatted_at_gmail.com)
Date: 11/30/04


Date: Tue, 30 Nov 2004 15:25:47 +0100

I've written a function (clean_string) to remove characters from a string,
but it looks clunky to me, and I'm sure there's a more 'C' like way of
doing it (still learning), comments and advice welcome...

--
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
        char * clean_string(const char *, const char *);
        char * string = "\t this is a string = sausages\n";
        char * chop = "\t\n= ";
        char *result = clean_string(string, chop);
        printf("[after] %s\n",result);
        return EXIT_SUCCESS;
}
char * clean_string(const char * string, const char * chop)
{
        char * inter;
        char * final = malloc(strlen(string)+1);
        strcpy(final, string);
        while((inter = strpbrk(final, chop)) != NULL)
        {
                int size_end = strlen(inter);
                int size_start = strlen(final) - size_end;
                char mod[6];
                final = (char *)realloc(final,size_start + size_end + 1);
                sprintf(mod, "%%.%ds%%s",size_start);
                sprintf(final,mod,string,inter+1);
                string = final;
        }
        return(final);
}
-- 
results in: 
[after] thisisastringsausages


Relevant Pages

  • Re: socket communication: send & receive doesnt work right
    ... So I don't want to send a string as bytes. ... public void send_doubles(double vals, int len) throws ... // send a short acknowledgement to the server ... char *result; ...
    (microsoft.public.win32.programmer.networks)
  • Re: [PATCH] markers: modpost
    ... pointers to the name/format string pairs. ... The same can then be done with modules using the __markers section. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: [PATCH] markers: modpost
    ... This adds some new magic in the MODPOST phase for CONFIG_MARKERS. ... will be a neighbor of its format string. ... +static void read_markers(const char *fname) ... int main ...
    (Linux-Kernel)
  • Re: Is this code totaly a shit?
    ... | void UppStrg(char *Low, char *Upp, int cnt); ... whitespace-delimited string. ... You're also assuming that the representations of the characters ...
    (comp.lang.c)
  • Re: A string collection abstract data type
    ... duplicate string in Insert, InsertAt, ReplaceAt; ... used int instead of size_t for count and size for consistency with API. ... char *(StringCollection *SC, int idx, ... static int IsReadOnly; ...
    (comp.lang.c)