F
fatted
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);
}
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);
}